How to add a separate css file in particular in mvc4?

Actually I have a main page and I am adding this main page to another view (Index.cshtml), now I want to add another separate css file to the Index.cshtml view.

+6
source share
3 answers

In the main section of the main page (for example, _Layout.cshtml) add a call to RenderSection. The header section may look like this:

<head> <meta charset="utf-8" /> <meta name="description" content="The content description" /> <link rel="shortcut icon" href="@Url.Content("~/Content/images/favicon.ico")" /> <title>@ViewBag.Title</title> @RenderSection("css", false) </head> 

Then in your index.cshtml use the section to add the css link:

 @section css { <link href="@Url.Content("~/css/style.css")" rel="stylesheet"/> } 

Please note that "css" is a unique name for your section, and it must match. You can also use this section in any view you want. The part you specify in the css section will be displayed in the header of your html, only where you place the placeholder RenderSection in your _Layout.cshtml.

+24
source

It's a bad practice, but you can just add the html link tag or script tag to the top of the view, modern browsers will do it anyway. This does not always have to be at the head of the main page.

+1
source

You can use Razor sections or a collection of strings and save it in ViewBag.CSS and then make it on the layout, or you can use javascript if you are not using a razor

 var $ = document; // shortcut var cssId = 'myCss'; // you could encode the css path itself to generate id.. if (!$.getElementById(cssId)) { var head = $.getElementsByTagName('head')[0]; var link = $.createElement('link'); link.id = cssId; link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'http://website.com/css/stylesheet.css'; link.media = 'all'; head.appendChild(link); } 
0
source

Source: https://habr.com/ru/post/925751/


All Articles