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");
}
}
{
[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.
- With the ActionName attribute you can specify what method name MVC pipeline should look while invoking the action method.
- First rename the POST Delete() controller method to DeleteOnConfirmation to fix method overloading related compilation error.
- 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");
}
}
{
[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