views:

48

answers:

1

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.

+2  A: 

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.

Darin Dimitrov
That is why I split them. I was hoping to have a scenario where I had a method that handled with an ID and one without the ID because it could be null. Essentially the id parameter here will act like a filter. So if it is there I want to get all the entities that belong to a group. If there is no id I just want it to get all entities. Is there a better way of doing this?
uriDium
Shouldn't your verb be on the other Index? Seems to me that the one without the parameter wouldn't need the verb and the other one would be more likely to have it...
BenAlabaster