Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 376
JohnOpincar Avatar asked Jan 19 '11 19:01

JohnOpincar


People also ask

Can you mix MVC and Razor pages?

You can add support for Pages to any ASP.NET Core MVC app by simply adding a Pages folder and adding Razor Pages files to this folder.

What is difference between View and Razor view?

The Razor View Engine is a bit slower than the ASPX View Engine. Razor provides a new view engine with streamlined code for focused templating. Razor's syntax is very compact and improves readability of the markup and code. By default MVC supports ASPX (web forms) and Razor View Engine.

Which keyword of Razor syntax is used to render the view content in the layout page as body content?

The @section directive is used in conjunction with MVC and Razor Pages layouts to enable views or pages to render content in different parts of the HTML page.


1 Answers

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.

like image 99
marcind Avatar answered Oct 22 '22 07:10

marcind