Thursday, 13 December 2018

asp.net mvc - How to reference a .css file on a razor view?



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 tags to work with, but not so in one of your non-layout views. Where do the tags go?



Answer



For CSS that are reused among the entire site I define them in the section of the _Layout:





@RenderSection("Styles", false)



and if I need some view specific styles I define the Styles section in each view:




@section Styles {

}


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.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...