2017-09-15 58 views
0

在.NET MVC中,我發現它始終遵循以下命名約定:控制器中的RouteName,它是一個名爲'RouteName.cshtml'的視圖。.Net MVC控制器不同的路由名稱使用相同的cshtml作爲視圖

我的問題是如何使用不同的RouteName使用SAME cshtml文件?

+0

的可能的複製[如何返回ActionResult與特定的視圖(不是控制器名稱)](https://stackoverflow.com/questions/26359192/how-to-return-actionresult-with-specific-view-not-the-controller-name) – mjwills

回答

1

默認視圖()方法的默認匹配操作名稱,但您可以使用View(String)方法來指定路徑所需CSHTML,像下面的例子:

// in action method that is *not* RouteName 
return View("RouteName"); 
+0

謝謝。目前,我'返回視圖(myViewModel)',你能告訴我在哪裏可以找到API,以便我可以指定路由名稱和模型到我的視圖? – n179911

+0

請訪問https://msdn.microsoft.com/zh-CN/library/system.web.mvc.controller.view(v=vs.118).aspx#M:System.Web.Mvc.Controller 。查看 您正在尋找的內容聽起來像是重載(string,object)的參數列表,其中字符串參數是視圖名稱,而對象參數是您的模型。 –

0

你可以使用partials重新使用CSHTML塊;取決於你試圖解決的問題,這可能是更好的解決方案。

你能編輯你的問題並添加更多的上下文嗎?爲什麼需要從多個ActionResult方法呈現相同的cshtml?你想達到什麼目的?

0

例如,有一個名爲About.cshtml 鑑於你有2點作用的方法和他們兩個都使用About.cshtml

所以,你可以嘗試

public ActionResult Index() 
     { 
     var model = "view model"; 
     // Pass view model as the second parameter 
     return View("About", model); 
     } 

public ActionResult About() 
     { 
      ViewBag.Message = "Your application description page."; 
      // Not need pass view name because view name and action method name are same (About 
      return View(); 
     } 
相關問題