03 June 2015

ActionName attribute in ASP.NET MVC

Using HttpGet and HttpPost ActionMethodAttribues, you can select between a HTTP POST and HTTP GET actions. But if you have same method signatures for your action methods in the controller class, the C# compiler will produce the below compilation error.

Type '..Controller' already defines a member called 'Delete' with the same parameter types.

Controller class with error

public class CustomerController : Controller
{
  [HttpGet]
  public ActionResult Delete(string customerId)
  {
     return View("ConfirmDelete", customerId);
  }

  [HttpPost]
  public ActionResult Delete(string customerId)
  {
    return RedirectToAction("List");
  }
}

Solution with ActionName attribute

Let’s see how we can fix the above error by making use ActionName attribute.

  1. With the ActionName attribute you can specify what method name MVC pipeline should look while invoking the action method.
  2. First rename the POST Delete() controller method to DeleteOnConfirmation to fix method overloading related compilation error.
  3. Then apply ActionName attribute to DeleteOnConfirmation() method by specifying "Delete" as the name.

Controller class with the fix

public class CustomerController : Controller
{
  [HttpGet]
  public ActionResult Delete(string customerId)
  {
    return View("ConfirmDelete", customerId);
  }

  [ActionName("Delete")]
  [HttpPost]
  public ActionResult DeleteOnConfirmation(string customerId)
  {
    // STEP1: Delete the customer in Database.
    return RedirectToAction("List");
  }
}

Benefits on ActionName attribute

By using ActionName attribute, now you can make the a URL with same action name and parameters maps to a different .NET method action method in your controller class.

  • HTTP GET "http://localhost/customer/delete/123" mapped to Delete action method.
  • HTTP POST "http://localhost/customer/delete/123" mapped to DeleteOnConfirmation action method.

No comments:

Post a Comment