In my mvc project I need to rename an action. After finding ActionName attribute I was thinking that the only thing that I have to do in order to rename HomeController.Index action to start is to add that attribute.
After I set:
[ActionName("Start")]
public ActionResult Index()
The action no longer find the view. It looks for start.cshtml view. Also Url.Action("Index", "home")
does not generate correct link.
Is this the normal behavior?
That is the consequence of using ActionName attribute. Thee view should be named after the action, not after the method.
Here is more
you need to return in the action:
return View("Index");//if 'Index' is the name of the view
This is normal behaviour.
The purpose of the ActionName
attribute seems to be for scenarios where you can end up with 2 identical actions which differ only in terms of the requests they handle. If you end up with actions like those, the compiler complains with this error:
Type YourController already defines a member called YourAction
with the
same parameter types.
I've not seen it happen in many scenarios yet, but one where it does happen is when deleting records. Consider:
[HttpGet]
public ActionResult Delete(int id)
{
var model = repository.Find(id);
// Display a view to confirm if the user wants to delete this record.
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
repository.Delete(id);
return RedirectToAction("Index");
}
Both methods take the same parameter types and have the same name. Although they are decorated with different HttpX
attributes, this isn't enough for the compiler to distinguish between them. By changing the name of the POST action, and marking it with ActionName("Delete")
, it allows the compiler to differentiate between the two. So the actions end up looking like this:
[HttpGet]
public ActionResult Delete(int id)
{
var model = repository.Find(id);
// Display a view to confirm if the user wants to delete this record.
return View(model);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
repository.Delete(id);
return RedirectToAction("Index");
}