如何使用Asp.Net MVC 3和Razor查看特定于视图的<head>内容?

Joh*_*car 32 stylesheet razor asp.net-mvc-3

除了已经在_Layout.cshtml中链接的内容之外,我还希望链接某些视图中的特定样式表.对于非剃刀,我看到使用内容占位符.我怎么为Razor做这个?

mar*_*ind 45

Razor中内容占位符的等价物是部分.

在你的_Layout.cshtml中:

<head>
@RenderSection("Styles", required: false)
</head>
Run Code Online (Sandbox Code Playgroud)

然后在您的内容页面中:

@section Styles {
    <link href="@Url.Content("~/Content/StandardSize.css")" />
}
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是将您的样式放入ViewBag/ViewData:

在你的_Layout.cshtml中:

<head>
    @foreach(string style in ViewBag.Styles ?? new string[0]) {
        <link href="@Url.Content(style)" />
    }
</head>
Run Code Online (Sandbox Code Playgroud)

在您的内容页面中:

@{
    ViewBag.Styles = new[] { "~/Content/StandardSize.css" };
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为视图页面在布局之前执行.

  • 这也是向头部添加视图特定脚本引用的好方法. (2认同)