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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With