2012-01-29 45 views
1

在我的mvc項目中,我需要重命名一個動作。找到ActionName屬性後,我在想,爲了重命名HomeController.Index行動,我必須做的唯一事情就是添加該屬性。ASP MVC ActionNameAttribute

後,我設置:

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

行動再也找不出視圖。它查找start.cshtml視圖。 Url.Action("Index", "home")也不會生成正確的鏈接。

這是正常的行爲?

+0

我們使用了那個糟糕的'ActionName'屬性,我們將其刪除。這會破壞你的靈活性,你最好找到其他解決方案。 – gdoron 2012-01-29 13:51:49

回答

0

你需要在行動回報:

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

正在使用ActionName屬性的後果。你的觀點應該以行動命名,而不是在方法之後。

Here is more

+0

然而整個事情都是有缺陷的。對於搜索引擎優化,帶連字符的URL比下劃線或將關鍵字放在一起更好。該語言不允許使用連字符定義方法,因此可以使用ActionName屬性。問題在於即使在actionname屬性中使用連字符,剃鬚刀引擎也無法找到視圖,即使它在那裏。 – 2014-12-10 18:21:58

0

這是正常現象。

ActionName屬性的用途似乎適用於您可以最終得到2個相同的操作,這些操作僅在處理請求方面有所不同。如果你最終像那些動作,編譯器會抱怨這個錯誤:

Type YourController already defines a member called YourAction with the same parameter types.

我還沒有看到它在許多情況下還沒有發生,但是一個如果它確實刪除記錄時發生。考慮:

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