I know how to set .css files on the _Layout.cshtml file, but what about applying a stylesheet on a per-view basis?
My thinking here is that, in _Layout.cshtml, you have <head>
tags to work with, but not so in one of your non-layout views. Where do the <link>
tags go?
This question is related to
css
asp.net-mvc
razor
I prefer to use the razor html helper from Client Dependency dll
Html.RequireCss("yourfile", 9999); // 9999 is loading priority
Using
@Scripts.Render("~/scripts/myScript.js")
or
@Styles.Render("~/styles/myStylesheet.css")
could work for you.
You can this structure in Layout.cshtml file
<link href="~/YourCssFolder/YourCssStyle.css" rel="stylesheet" type="text/css" />
layout works the same as an master page. any css reference that layout has, any child pages will have.
I tried adding a block like so:
@section styles{
<link rel="Stylesheet" href="@Href("~/Content/MyStyles.css")" />
}
And a corresponding block in the _Layout.cshtml file:
<head>
<title>@ViewBag.Title</title>
@RenderSection("styles", false);
</head>
Which works! But I can't help but think there's a better way. UPDATE: Added "false" in the @RenderSection
statement so your view won't 'splode when you neglect to add a @section
called head
.
Source: Stackoverflow.com