【发布时间】:2010-05-16 19:48:10
【问题描述】:
我有两个动作,一个接受 ViewModel,一个接受两个参数,一个字符串和一个 int,当我尝试发布到该动作时,它给了我一个错误,告诉我当前请求在两者之间不明确行动。
是否可以向路由系统指示哪个动作是相关的,如果是,它是如何完成的?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-2 routing asp.net-mvc-routing
我有两个动作,一个接受 ViewModel,一个接受两个参数,一个字符串和一个 int,当我尝试发布到该动作时,它给了我一个错误,告诉我当前请求在两者之间不明确行动。
是否可以向路由系统指示哪个动作是相关的,如果是,它是如何完成的?
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-2 routing asp.net-mvc-routing
你可以用 HttpGet HttpPost 来装饰它
查看“覆盖 HTTP 方法动词”
http://www.asp.net/learn/whitepapers/what-is-new-in-aspnet-mvc
您还可以使用 ActionName 属性。在“ActionNameAttribute”下查看
http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx
【讨论】:
You can't overload controller actions,尽管正如 Raj 所说,您可以通过允许它们响应不同的请求(获取、发布等)来区分它们。
您可能还会发现这很有帮助:How a Method Becomes An Action。
【讨论】:
一个简化的例子:
[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");
}
如果您需要两个具有完全相同的签名(相同名称和完全相同数量的相同类型的参数)的操作,在这种情况下,您将不得不使用另一个属性,例如这个:
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));
}
【讨论】: