How to add individual css file in particular view

2019-04-07 22:05发布

问题:

Actually I've a master page and I'm adding this master page into another view (Index.cshtml), now I want to add another individual css file into Index.cshtml view.

回答1:

In the head section of your master page (e.g. _Layout.cshtml) add a RenderSection call. Your header section could 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 your css link:

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

Note that "css" is a unique name for your section and it needs to match. You can also use this section in any view you want. The part you specify within the css section will then be rendered within the head-tag of your html, just where you put the RenderSection placeholder in your _Layout.cshtml.



回答2:

Bad practice but you can Just add a html link tag or script tag to the top of the view, modern browsers will still render this. It doesn't always need to be in the head of the master page



回答3:

You can use Razor sections, or a string collection and store it in ViewBag.CSS, and later render it on the layout, or you can use javascript if you are not profficient with 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);
}