ASP.net MVC 4中的条件@Scripts.Render

6
在我的_Layout.cshtml页面中,我希望根据显示的视图仅包含特定的@Styles.Render捆绑包。例如,一个页面可能使用jQueryUI库,而另一个页面可能没有,如果不必要下载库,则不想进行请求。我可以在我的_layout.cshtml中使用条件语句来实现这一点吗?

1
为什么不使用布局来输出所有视图都需要的基线样式/脚本,然后让各个视图使用@section添加其他文件呢? - Tim M.
2个回答

6
在你的_Layout.cshtml页面中添加一个@RenderSection
@RenderSection("Page_Styles", required: false)

然后在你的个人视图中,你可以根据需要添加样式

@section Page_Styles {
    @Styles.Render("~/bundles/style/foo")
}

同样的想法适用于脚本。
@RenderSection("Scripts", required: false)

@section Scripts {
    @Scripts.Render("~/bundles/jqueryui")
}

4

最好在你的_layout.cshtml文件中创建一个部分,然后在视图内添加内容到该部分。对于那些不想在每个页面都加载的样式表,我会这样做:

<!-- _layout.cshtml -->
<head>
    <!-- will load on every page -->
    <link rel="stylesheet" href="common.css" />
    <!-- will load on only the views where you have @section CSS -->
    @RenderSection("CSS", false)
</head>

然后是视图:

<p>some content</p>
@section CSS { @Styles.Render("~/mystylesheet.css") }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接