我正在尝试从 _Layout 文件中渲染不同的部分视图,具体取决于我在控制器中的功能。
部分视图位于网站的右栏中,位于 _Layout 中,如下所示:
<aside id="right">
@Html.Partial("RightPartial")
</aside>
我想要做的是根据我所在的位置呈现不同的局部视图。如果我在索引视图中,我可能想要查看新闻,而在关于视图中,我可能想要查看电话号码或其他内容。
感谢任何帮助:)
我正在尝试从 _Layout 文件中渲染不同的部分视图,具体取决于我在控制器中的功能。
部分视图位于网站的右栏中,位于 _Layout 中,如下所示:
<aside id="right">
@Html.Partial("RightPartial")
</aside>
我想要做的是根据我所在的位置呈现不同的局部视图。如果我在索引视图中,我可能想要查看新闻,而在关于视图中,我可能想要查看电话号码或其他内容。
感谢任何帮助:)
@{
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");
}
}