【问题标题】:How Can I Have View-Specific <head> contents Using Asp.Net MVC 3 and Razor?如何使用 Asp.Net MVC 3 和 Razor 获得特定于视图的 <head> 内容?
【发布时间】:2011-06-12 00:18:54
【问题描述】:

除了 _Layout.cshtml 中已经链接的内容之外,我还想在某些视图中链接特定样式表。对于非 Razor,我看到使用内容占位符。我将如何为 Razor 执行此操作?

【问题讨论】:

    标签: asp.net-mvc-3 razor stylesheet


    【解决方案1】:

    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" };
    }
    

    这是因为视图页面在布局之前执行。

    【讨论】:

    • 这也是向头部添加视图特定脚本引用的好方法。
    • 替代解决方案适用于尚未将其解决方案转换为使用 Razor 的人。谢谢!
    【解决方案2】:

    令人惊讶的是(对我而言),asp:ContentPlaceHolder 确实有效。不过看起来很不光彩。不知道有没有别的办法?

    具体来说,您将&lt;asp:ContentPlaceHolder ID="HeadContent" runat="server" /&gt; 放入您的_layout.cshtml 和

    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> 
        <link href="@Url.Content("~/Content/StandardSize.css")" rel="stylesheet" type="text/css" />
    </asp:Content>
    

    在你看来。

    【讨论】:

    • 只有在你看来它有效。你看过生成的 HTML 吗?
    • 你是对的。我刚刚看到应用了我想要的样式,但我没有检查 HTML。我想知道 Razor 是如何处理服务器标签的。
    猜你喜欢
    • 2011-11-25
    • 2012-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多