在我的mvc项目中,我需要重命名一个动作。在找到ActionName属性后,我在想,为了将HomeController.Index操作重命名为start,我唯一需要做的就是添加该属性。
在我设置之后:
[ActionName("Start")]
public ActionResult Index()该操作不再找到视图。它查找start.cshtml视图。此外,Url.Action("Index", "home")不会生成正确的链接。
这是正常行为吗?
发布于 2012-01-29 21:52:16
这就是使用ActionName属性的结果。视图应该以动作命名,而不是以方法命名。
Here is more
发布于 2012-01-29 21:49:08
您需要在操作中返回:
return View("Index");//if 'Index' is the name of the view发布于 2012-01-29 22:05:16
这是正常行为。
ActionName属性的用途似乎是用于这样的场景:您可以得到两个相同的操作,它们只是在处理的请求方面有所不同。如果您以类似的操作结束,编译器将报告以下错误:
类型YourController已经使用相同的参数类型定义了一个名为
YourAction的成员。
我还没有在很多场景中看到它的发生,但它确实发生在删除记录的时候。考虑一下:
[HttpGet]
public ActionResult Delete(int id)
{
var model = repository.Find(id);
// Display a view to confirm if the user wants to delete this record.
return View(model);
}
[HttpPost]
public ActionResult Delete(int id)
{
repository.Delete(id);
return RedirectToAction("Index");
}这两种方法都采用相同的参数类型,并且具有相同的名称。尽管它们使用不同的HttpX属性进行修饰,但这还不足以让编译器区分它们。通过更改POST操作的名称并将其标记为ActionName("Delete"),它允许编译器区分这两个操作。因此,操作最终看起来如下所示:
[HttpGet]
public ActionResult Delete(int id)
{
var model = repository.Find(id);
// Display a view to confirm if the user wants to delete this record.
return View(model);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
repository.Delete(id);
return RedirectToAction("Index");
}https://stackoverflow.com/questions/9053617
复制相似问题