开发者

How Can I Have View-Specific <head> contents Using Asp.Net MVC 3 and Razor?

开发者 https://www.devze.com 2023-02-05 19:47 出处:网络
I want to link a specific style sheet in certain Views in addition to what already gets linked in _Layout.cshtml.For non-Razor, I see using the content 开发者_C百科place holder.How would I do this for

I want to link a specific style sheet in certain Views in addition to what already gets linked in _Layout.cshtml. For non-Razor, I see using the content 开发者_C百科place holder. How would I do this for Razor?


The equivalent of content placeholders in Razor are sections.

In your _Layout.cshtml:

<head>
@RenderSection("Styles", required: false)
</head>

Then in your content page:

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

An alternative solution would be to put your styles into ViewBag/ViewData:

In your _Layout.cshtml:

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

And in your content page:

@{
    ViewBag.Styles = new[] { "~/Content/StandardSize.css" };
}

This works because the view page gets executed before the layout.


Surprisingly (to me), asp:ContentPlaceHolder does work. Seems very unrazorish though. I wonder if there's another way?

Specifically, you put <asp:ContentPlaceHolder ID="HeadContent" runat="server" /> in your _layout.cshtml and

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

in your view.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号