2013-05-10 96 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