Tutorial :How Does One Differentiate Between Routes POSTed To In Asp.Net MVC?



Question:

I have two actions, one that accepts a ViewModel and one that accepts two parameters a string and an int, when I try to post to the action, it gives me an error telling me that the current request is ambiguous between the two actions.

Is it possible to indicate to the routing system which action is the relevant one, and if it is how is it done?


Solution:1

You can decorate it with HttpGet HttpPost

Look under "Overriding the HTTP Method Verb"

http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvc

You can also use the ActionName attribute. Look under "ActionNameAttribute"

http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx


Solution:2

You can't overload controller actions, though as Raj said, you can differentiate them by allowing them to respond to different requests (get, post, etc).

You might also find this helpful: How a Method Becomes An Action.


Solution:3

This is how it's done

A simplified example:

[HttpGet] // this attribute is't necessary when there are only 2 actions with the same name  public ActionResult Update(int id)  {      return View(new Repository().GetProduct(id));  }    [HttpPost]  public ActionResult Update(int id, Product product)  {      // handle POST data      var repo = new Repository();      repo.UpdateProduct(product);      return RedirectToAction("List");  }  

And if you'd need two actions that would have completely same signature (same name and exactly the same number of parameters of the same type) in that case you would have to use another attribute like this:

public ActionResult SomeAction(int id)  {      return View(new Repository().GetSomething(id));  }    [HttpPost]  [ActionName("SomeAction")]  public ActionResult SomeActionPost(int id)  {      // handle POST data      var repo = new Repository();      repo.UpdateTimestamp(id);      return View(repo.GetSomething(id));  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »