[ASP.NET MVC] Controllers – Action Selectors

Actions are public methods in controller classes. MVC provides attributes to tweak how the actions can be selected based on the name or the request verbs.

1. [ActionName]

The “ActionNameAttribute” class is used to set the action name to an action method.

public ActionNameAttribute(string name)

It has a single parameter “name“.

public class HomeController : Controller
{
  [ActionName("Help")]
  public ActionResult RetriveHelpInfo()
  {
    ViewBag.Message = "Your contact page.";
    return View();
  }
}

If you access the action using the url “/Home/RetriveHelpInfo“, you will get a 404(Not found) error. The correct url is “/Home/Help“.

[Note] When you create a view, make sure the name of the view is “Help.cshtml”, not “RetriveHelpInfo.cshtml”.

 

2. [AcceptVerbs]

The “AcceptVerbsAttribute” class specifies which HTTP verbs an action method will respond to.

public AcceptVerbsAttribute(params string[] verbs)
public AcceptVerbsAttribute(HttpVerbs verbs)

It is a generic way to map the actions to HTTP verbs. The “Get” request is the default for actions so you do not need to use the attribute.

public class ProductController : Controller
{
  [AcceptVerbs(HttpVerbs.Get)]
  public ActionResult Edit(int id)
  {
    Product p = ...;  // retrieve the product
    return View(p);
  }

  [AcceptVerbs(HttpVerbs.Post)]
  public ActionResult Edit(Product p)
  {
    if (ModelState.IsValid)
    {
      // Update the model
    }
    return View("Details", p);
  }
}

 

3. [HttpGet], [HttpPost]

Rather than using the general [AcceptVerbs] attribute, MVC provides the shortcut attributes.

  • HttpGetAttribute 
  • HttpDeleteAttribute 
  • HttpPostAttribute 
  • HttpPutAttribute
public class ProductController : Controller
{
  [HttpGet]
  public ActionResult Edit(int id)
  {
  }

  [HttpPost]
  public ActionResult Edit(Product p)
  {
  }
}

2 thoughts on “[ASP.NET MVC] Controllers – Action Selectors

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s