布局页面头:
<head>
<link href="@Url.Content("~/Content/themes/base/Site.css")"
rel="stylesheet" type="text/css" />
</head>
Run Code Online (Sandbox Code Playgroud)
应用程序需要的View(AnotherView):
<link href="@Url.Content("~/Content/themes/base/AnotherPage.css")"
rel="stylesheet" type="text/css" />
Run Code Online (Sandbox Code Playgroud)
和AnotherView有一个局部视图(AnotherPartial)需要:
<link href="@Url.Content("~/Content/themes/base/AnotherPartial.css")"
rel="stylesheet" type="text/css" />
Run Code Online (Sandbox Code Playgroud)
问题:我们如何将这些CSS文件链接添加到Layouthead和AnotherPartial链接到Layout头?
RenderSection不是一个好主意,因为AnotherPage可以有多个Partials.添加所有CSS到头部是没用的,因为它将动态更改(它取决于Anotherpages).
鉴于MVC3和Razor引擎,我得到了
_MasterLayout.cshtml
@RenderSection("JavaScript", required: false)
..
..
@RenderBody()
..
Run Code Online (Sandbox Code Playgroud)
View.cshtml与_ViewStart.cshtml中定义的_MasterLayout.cshtml
..
@Html.RenderAction("PartialView", "PartialController")
..
Run Code Online (Sandbox Code Playgroud)
PartialView.cshtml
..
@section JavaScript
{
........
}
..
Run Code Online (Sandbox Code Playgroud)
如何确保部分视图中的JavaScript最终出现在"主布局"部分中?
上述方案不起作用,因为局部视图没有定义主布局.另一方面,视图确实具有定义了RenderSection的布局.如果我将部分JavaScript从部分视图移动到View,Razor知道将其渲染到何处.但是,由于部分视图没有布局,因此它不知道如何处理部分JavaScript,因此不会将其呈现在任何地方.