开发者

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

I have two actions, one that accepts a ViewModel and one that acc开发者_如何学Goepts 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?


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


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.


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));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜