2013-05-10 93 views
0

我想從_Layout文件呈現不同的局部視圖,具體取決於我在哪個功能,控制器方面。呈現不同的局部視圖

的局部視圖是其中位於_layout像這樣的網站的右列:

<aside id="right"> 
@Html.Partial("RightPartial") 
</aside> 

我想要做的是根據我在哪裏呈現不同的局部視圖。 如果我在索引視圖中,我可能想要查看新聞,並在About視圖中查看電話號碼或其他內容。

欣賞現在根據這些變量的值任何幫助:)

回答

1
@{ 
    string currentAction = ViewContext.RouteData.GetRequiredString("action"); 
    string currentController = ViewContext.RouteData.GetRequiredString("controller"); 
} 

決定要渲染的部分。爲了避免污染布局我會寫一個自定義的HTML幫助:

<aside id="right"> 
    @Html.RightPartial() 
</aside> 

這可能是這樣的:

public static class HtmlExtensions 
{ 
    public static IHtmlString RightPartial(this HtmlHelper html) 
    { 
     var routeData = html.ViewContext.RouteData; 
     string currentAction = routeData.GetRequiredString("action"); 

     if (currentAction == "Index") 
     { 
      return html.Partial("IndexPartialView"); 
     } 
     else if (currentAction == "About") 
     { 
      return html.Partial("AboutPartialView"); 
     } 

     return html.Partial("SomeDefaultPartialView"); 
    } 
} 
+0

應該在哪裏「公共靜態類HtmlExtensions」走? – Mappan 2013-05-10 15:34:19

+1

無論你想要什麼。你可以有一個'Extensions'文件夾或任何你認爲正確的東西。這只是一種擴展方法,您需要將其納入視圖的範圍以便能夠調用它。或者將該類定義爲'@ using'指令的命名空間添加到視圖頂部,或將其添加到'〜/ Views/web.config'文件的''部分,並且定製助手將可用在所有的意見。 – 2013-05-10 15:34:59

+0

它的工作,非常感謝你。 – Mappan 2013-05-10 15:57:56