首页
学习
活动
专区
圈层
工具
发布

ASP
EN

Stack Overflow用户
提问于 2012-01-29 21:43:27
回答 3查看 2.5K关注 0票数 1

在我的mvc项目中,我需要重命名一个动作。在找到ActionName属性后,我在想,为了将HomeController.Index操作重命名为start,我唯一需要做的就是添加该属性。

在我设置之后:

代码语言:javascript
复制
[ActionName("Start")]
public ActionResult Index()

该操作不再找到视图。它查找start.cshtml视图。此外,Url.Action("Index", "home")不会生成正确的链接。

这是正常行为吗?

EN

回答 3

Stack Overflow用户

发布于 2012-01-29 21:52:16

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

Here is more

票数 2
EN

Stack Overflow用户

发布于 2012-01-29 21:49:08

您需要在操作中返回:

代码语言:javascript
复制
return View("Index");//if 'Index' is the name of the view
票数 0
EN

Stack Overflow用户

发布于 2012-01-29 22:05:16

这是正常行为。

ActionName属性的用途似乎是用于这样的场景:您可以得到两个相同的操作,它们只是在处理的请求方面有所不同。如果您以类似的操作结束,编译器将报告以下错误:

类型YourController已经使用相同的参数类型定义了一个名为YourAction的成员。

我还没有在很多场景中看到它的发生,但它确实发生在删除记录的时候。考虑一下:

代码语言:javascript
复制
[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"),它允许编译器区分这两个操作。因此,操作最终看起来如下所示:

代码语言:javascript
复制
[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");
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9053617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档