Asp.net mvc ASP MVC ActionNameAttribute

Asp.net mvc ASP MVC ActionNameAttribute,asp.net-mvc,asp.net-mvc-3,Asp.net Mvc,Asp.net Mvc 3,在我的mvc项目中,我需要重命名一个操作。在找到ActionName属性后,我想我必须做的唯一一件事是重命名HomeController.Index操作,以开始添加该属性 在我设定之后: [ActionName("Start")] public ActionResult Index() 该操作不再找到视图。它查找start.cshtml视图。另外,Url.Action(“Index”,“home”)不会生成正确的链接 这是正常行为吗?您需要在操作中返回: return View("Index"

在我的mvc项目中,我需要重命名一个操作。在找到ActionName属性后,我想我必须做的唯一一件事是重命名HomeController.Index操作,以开始添加该属性

在我设定之后:

[ActionName("Start")]
public ActionResult Index()
该操作不再找到视图。它查找start.cshtml视图。另外,
Url.Action(“Index”,“home”)
不会生成正确的链接


这是正常行为吗?

您需要在操作中返回:

return View("Index");//if 'Index' is the name of the view

这是使用ActionName属性的结果。视图应以操作命名,而不是以方法命名


这是正常的行为

ActionName
属性的用途似乎是针对这样的场景,即您最终可以执行两个相同的操作,而这两个操作仅在处理的请求方面有所不同。如果您最终执行了类似的操作,编译器会抱怨以下错误:

键入YourController已使用 相同的参数类型

我还没有在很多场景中看到这种情况发生,但在删除记录时确实发生了这种情况。考虑:

[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");
}

我们使用了那个糟糕的
ActionName
属性,并删除了它。这会破坏你的灵活性,你最好找到其他的解决方案。但整个事情都是有缺陷的。对于SEO来说,使用连字符的URL比下划线或将关键字放在一起要好。该语言不允许使用连字符定义方法,因此可以使用ActionName属性。问题是,即使actionname属性中有连字符,razor引擎也无法找到视图,即使它在那里。