简体   繁体   中英

Ambigous Routes Using ASP.Net MVC

So far I still have the standard routing. What I tried to do is

public Foo : Controller
{
    public ActionResult Index(int id)
    {
        return View("List", repo.GetForId(id));
    }

    public ActionResult Index()
    {
        return View("List", repo.GetAll());
    }
}

The URL I entered was localhost/Foo/Index. I was under the asumption that it was smart enough to figure out which method I wanted. All I get though is an error telling me that the call is ambigous. From reading the route tutorial I thought that this would work. What am I missing?

Sorry:

Duplicate. I am voting to close.

Method overloading (two actions with the same name) resolution is based on the HTTP verb. This means that if you want to have two actions with the same name you need to differentiate them by the HTTP verb they accept:

public ActionResult Index(int id)
{
    return View("List", repo.GetForId(id));
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index()
{
    return View("List", repo.GetAll());
}

Thus when you call GET /Home/Index the first action will be invoked and when you call POST /Home/Index the second one will be invoked.

Also note that you should probably use nullable integer as the id argument because if no parameter is passed in the request, the model binder will fail.

A RESTful way to handle this, following conventions that I would suggest you is this:

public ActionResult Index()
{
    return View(repo.GetAll());
}

public ActionResult Show(int id)
{
    return View(repo.GetForId(id));
}

which will allow you to handle both /Home/Index and /Home/Show/10 requests. You probably will have different views as well because the first one will be strongly typed to IEnumerable<T> while the second one to T .

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