【发布时间】:2011-02-23 04:59:41
【问题描述】:
假设我在多个文件夹中有多个视图。
还有一个菜单,根据视图文件夹的不同,里面会有不同的东西。
有没有办法在文件中(在@section 或其他东西中)模板化菜单并将其自动注入到主模板中? (可能是 /views/shared/_layout.cshtml)。
即像
/views/foo/menu.cshtml
@section menu
{
<li>item1</li>
<li>item2</li>
}
/views/bar/menu.cshtml
@section menu
{
<li>item1</li>
<li>item2</li>
<li>item3</li>
}
/views/shared/_Layout.cshtml
<blah blah blah>
<ul>
@if(IsSectionDefined("Menu"))
{
@RenderSection("Menu");
}
</ul>
@RenderBody()
</blah blah blah>
所以如果 localhost/foo/* 被调用 foo/menu 将被注入。 如果 localhost/bar/* 被调用 bar/menu 会被注入到 _Layout 等等。
我在想 2 个可能的注入点在 _ViewStart.cshtml 中或覆盖基本网页类,但问题仍然存在,如何注入该部分?
感谢 SLaks 将此添加到 _Layout.cshtml:
@{
var controller = Request.RequestContext.RouteData.GetRequiredString("controller");
if (File.Exists(HttpRuntime.AppDomainAppPath + @"\views\" + controller + @"\menu.cshtml"))
{
@Html.Partial("~/views/" + controller + "/menu.cshtml");
}
}
【问题讨论】:
标签: templates asp.net-mvc-3 razor