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?
layout works the same as an master page. any css reference that layout has, any child pages will have.
Scott Gu has an excellent explanation here
Using
or
could work for you.
https://stackoverflow.com/a/36157950/2924015
You can this structure in Layout.cshtml file
I prefer to use the razor html helper from Client Dependency dll
I tried adding a block like so:
And a corresponding block in the _Layout.cshtml file:
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
calledhead
.For CSS that are reused among the entire site I define them in the
<head>
section of the_Layout
:and if I need some view specific styles I define the
Styles
section in each view:Edit: It's useful to know that the second parameter in @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will blissfully ignore the fact that there is no "Styles" section defined in your view. If true, the view won't render and an error will be thrown unless the "Styles" section has been defined.