2010-02-16 58 views
0

我試圖實現用戶友好的URL,同時保留現有的路線,並能夠使用頂部的ActionName標籤我的控制器(Can you overload controller methods in ASP.NET MVC?如何在ASP.NET MVC中共享2個控制器的控制器邏輯,在那裏他們被覆蓋

的我有2個控制器:

ActionName("UserFriendlyProjectIndex")] 
public ActionResult Index(string projectName) { ... } 

public ActionResult Index(long id) { ... } 

基本上,我試圖做的是我存放用戶友好的URL數據庫中的每個項目。

如果用戶輸入的URL /項目/ TopSecretProject/,動作UserFriendlyProjectIndex被調用。我做一個數據庫查找,如果一切都檢出,我想要應用在索引操作中使用的完全相同的邏輯。

我基本上是爲了避免編寫重複的代碼。我知道我可以將通用邏輯分解成另一種方法,但我想知道在ASP.NET MVC中是否有內置的方法。

有什麼建議嗎?

我嘗試以下,我去查看找不到錯誤消息:

[ActionName("UserFriendlyProjectIndex")] 
public ActionResult Index(string projectName) 
{ 
    var filteredProjectName = projectName.EscapeString().Trim(); 

    if (string.IsNullOrEmpty(filteredProjectName)) 
     return RedirectToAction("PageNotFound", "Error"); 

    using (var db = new PIMPEntities()) 
    { 
     var project = db.Project.Where(p => p.UserFriendlyUrl == filteredProjectName).FirstOrDefault(); 
     if (project == null) 
      return RedirectToAction("PageNotFound", "Error"); 

     return View(Index(project.ProjectId)); 
    } 
} 

這裏的錯誤消息:

The view 'UserFriendlyProjectIndex' or its master could not be found. The following locations were searched: 
~/Views/Project/UserFriendlyProjectIndex.aspx 
~/Views/Project/UserFriendlyProjectIndex.ascx 
~/Views/Shared/UserFriendlyProjectIndex.aspx 
~/Views/Shared/UserFriendlyProjectIndex.ascx 
Project\UserFriendlyProjectIndex.spark 
Shared\UserFriendlyProjectIndex.spark 

我用SparkViewEngine作爲視圖引擎和LINQ如果有幫助的話 謝謝!

回答

0

對不起,它看起來像我回答我自己的問題!

我把我的「包裝」控制器中的索引控制器的調用返回,然後我在索引控制器中指定視圖名稱。

ActionName("UserFriendlyProjectIndex")] 
public ActionResult Index(string projectName) 
{ 
    //... 
    //var project = ...; 
    return Index(project.ProjectId); 
} 

public ActionResult Index(long id) 
{ 
    //... 
    return View("Index", project); 
} 
1

,正如另外這款本,可能付出去優化它僅命中一次數據庫的項目...

ActionName("UserFriendlyProjectIndex")] 
public ActionResult Index(string projectName) 
{ 
    //... 
    //var project = ...; 
    return IndexView(project); 
} 

public ActionResult Index(long id) 
{ 
    //... 
    //var project = ...; 
    return IndexView(project); 
} 

private ViewResult IndexView(Project project) 
{ 
    //... 
    return View("Index", project); 
}