0

If I have the following two action methods:

public ActionResult Index(String id) { //do something based on id }

public ActionResult Index(MyCustomViewModel vm) { //do something based on view model provided }

I am getting an ambiguous method error. How can I setup the routes to ensure both work ?

1 Answer 1

1

You can't have two actions with the same name and the same HTTP verb and routes cannot help you here. You need to specify a different verb:

public ActionResult Index(string id) { ... }

[HttpPost]
public ActionResult Index(MyCustomViewModel vm) { ... }
Sign up to request clarification or add additional context in comments.

4 Comments

Even after adding the Post filter attribute, it still goes to Index(string id) action method with id = null. How can I redirect it to Post Action method using Html.ActionLink helper?
@nEEbz, you can't. Html.ActionLink always sends a GET request. You could use an HTML <form> which could send a POST request or use javascript to AJAXify your ActionLink and send an AJAX POST request instead of the default GET.
Ok I might be sounding very dumb but isn't that what Model Binding all about? I send parameters in query string and MVC intelligently binds them to the view model object and passes it to the action method?
@nEEbz, yes that's exactly what the model binder does. But in your case you have two methods with the same name which could be invoked over the same HTTP verb on the same controller and the action invoker doesn't know which one to invoke. Suppose that you call /index?id=123 on GET. Which one of the two methods would you invoke? What if you wanted to invoke the second method and pass all other parameters to empty string? It is impossible to make the distinction. The possible workarounds are to rename one of the methods or change the HTTP verb as suggested in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.