JohnOpincar
JohnOpincar

Reputation: 5813

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

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 place holder. How would I do this for Razor?

Upvotes: 33

Views: 9069

Answers (1)

marcind
marcind

Reputation: 53183

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.

Upvotes: 48

Related Questions