【发布时间】:2011-06-12 00:18:54
【问题描述】:
除了 _Layout.cshtml 中已经链接的内容之外,我还想在某些视图中链接特定样式表。对于非 Razor,我看到使用内容占位符。我将如何为 Razor 执行此操作?
【问题讨论】:
标签: asp.net-mvc-3 razor stylesheet
除了 _Layout.cshtml 中已经链接的内容之外,我还想在某些视图中链接特定样式表。对于非 Razor,我看到使用内容占位符。我将如何为 Razor 执行此操作?
【问题讨论】:
标签: asp.net-mvc-3 razor stylesheet
Razor 中相当于内容占位符的是部分。
在您的 _Layout.cshtml 中:
<head>
@RenderSection("Styles", required: false)
</head>
然后在您的内容页面中:
@section Styles {
<link href="@Url.Content("~/Content/StandardSize.css")" />
}
另一种解决方案是将您的样式放入 ViewBag/ViewData:
在您的 _Layout.cshtml 中:
<head>
@foreach(string style in ViewBag.Styles ?? new string[0]) {
<link href="@Url.Content(style)" />
}
</head>
在您的内容页面中:
@{
ViewBag.Styles = new[] { "~/Content/StandardSize.css" };
}
这是因为视图页面在布局之前执行。
【讨论】:
令人惊讶的是(对我而言),asp:ContentPlaceHolder 确实有效。不过看起来很不光彩。不知道有没有别的办法?
具体来说,您将<asp:ContentPlaceHolder ID="HeadContent" runat="server" /> 放入您的_layout.cshtml 和
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<link href="@Url.Content("~/Content/StandardSize.css")" rel="stylesheet" type="text/css" />
</asp:Content>
在你看来。
【讨论】: