Automatic injection of templated html into razor section based on view folder
Say i have several views in several folders.
And there is a menu, which will have different things in it depending on the view folder.
Is there a way to template out a menu in a file (in a @section
or something) and have it automatically injected into the main template? (probably /views/shared/_layout.cshtml).
i.e. something like
/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>
So if localhost/foo/* is called foo/menu will be injected. If localhost/bar/* is called bar/menu will be injected into _Layout and so on and so forth.
I'm thinking 2 possible injection points are in the _ViewStart.cshtml or overriding the base webpage class, but the question remains, how to inject the section?
Thanks to SLaks added this to _Layout.cshtml:
@{
var controller = Request.RequestContext.RouteData.GetRequiredString("controller");
if (File.Exists(HttpRuntime.AppDomainAppPath + @"\vi开发者_如何转开发ews\" + controller + @"\menu.cshtml"))
{
@Html.Partial("~/views/" + controller + "/menu.cshtml");
}
}
Like this:
@Html.Partial("~/Views/" + name + "/menu.cshtml")
精彩评论