is it possible to have 2 actions with the same name and parameters but one's a post, the other a get? e.g Delete(id)
and [HttpPost]Delete(id)
...i get an error saying that this is not allowed...
While ASP.NET MVC will allow you to have two actions with the same name, . NET won't allow you to have two methods with the same signature - i.e. the same name and parameters. You will need to name the methods differently use the ActionName attribute to tell ASP.NET MVC that they're actually the same action.
This will fail when you will call these because the MVC framework won't know which one to call. You have two solutions to make MVC routing know which action to use. First, you can change the name.
ActionLink() does not link to a view. It creates a link to a controller action. The first parameter is the link text, and the second parameter is the name of the controller action.
Yes, it's possible. Just use ActionName attribute on one action:
public ActionResult Delete(int id)
{
//...
return View();
}
[HttpPost]
[ActionName("Delete")]
public ActionResult Delete_Post(int id)
{
//...
return View();
}
The reason you get the error that it is not allowed is because C# itself gets confused. While in MVC you can add attributes to specify whether a function is HttpGet or HttpPost, that doesn't help C# determine the difference between one or the other. In order to have 2 functions with exactly the same name, the parameter list needs to be different.
As frennky pointed out, the ActionName attribute works in MVC because MVC uses aliases as part of the process for determining which action to call (along with attributes, but not parameters).
As a side note, it's probably best not to have a Delete action on a GET request. You don't want a crawler or some other bot accidently hitting the wrong link :P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With