简体   繁体   中英

ASP.NET MVC - How do action names affect the url?

Using MVC out of the box I found the generated URLs can be misleading and I wanted to know if this can be fixed or if my approach/understanding is wrong.

Suppose I have a CreateEgg page, which has a form on it, and once the form is filled in and submitted the user is taken to a ListEggs page with the new egg in it.

So my egg controller will look some thing like this:

public class EggController : Controller
{
    public void Add()
    {
        //do stuff

        RenderView("CreateEgg", viewData);
    }

    public void Create()
    {
        //do stuff

        RenderView("ListEggs", viewData);
    }
}

So my first page will have a url of something like http://localhost/egg/add and the form on the page will have an action of:

using (Html.Form<EggController>(c => c.Create())

Meaning the second page will have a url of http://localhost/Egg/Create , to me this is misleading, the action should be called Create, because im creating the egg, but a list view is being displayed so the url of http://localhost/Egg/List would make more scene. How do I achieve this without making my view or action names misleading?

The problem is your action does two things, violating the Single Responsibility Principle.

If your Create action redirects to the List action when it's done creating the item, then this problem disappears.

ActionVerbs Outlined in Scott Gu's post seem to be a good approch;

Scott says:

You can create overloaded implementations of action methods, and use a new [AcceptVerbs] attribute to have ASP.NET MVC filter how they are dispatched. For example, below we can declare two Create action methods - one that will be called in GET scenarios, and one that will be called in POST scenarios

[AcceptVerbs("GET")]
public object Create() {}
[AcceptVerbs("POST")]
public object Create(string productName, Decimal unitPrice) {}

菲尔·哈克(Phil Haack)的方法如何成为行动

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM