【问题标题】:ASP MVC ActionNameAttributeASP MVC 动作名称属性
【发布时间】:2012-04-11 14:22:31
【问题描述】:

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

我设置后:

[ActionName("Start")]
public ActionResult Index()

动作不再找到视图。它寻找 start.cshtml 视图。 Url.Action("Index", "home") 也不会生成正确的链接。

这是正常行为吗?

【问题讨论】:

  • 我们使用了那个糟糕的ActionName 属性,我们将其删除。它会破坏你的灵活性,你最好找到其他解决方案。

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

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

Here is more

【讨论】:

  • 然而整个事情还是有缺陷的。对于 SEO,带有连字符的 URL 比下划线或将关键字放在一起更好。该语言不允许使用连字符定义方法,因此可以使用 ActionName 属性。问题是即使在 actionname 属性中使用连字符,剃刀引擎也无法找到视图,即使它存在。
【解决方案2】:

你需要在动作中返回:

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

【讨论】:

    【解决方案3】:

    这是正常行为。

    ActionName 属性的用途似乎是针对这样的场景,即您可以最终得到 2 个相同的操作,这些操作仅在它们处理的请求方面有所不同。如果你最终执行了类似的操作,编译器会报错:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-28
      • 2012-10-06
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多