How to add individual css file in particular view

2019-04-07 21:50发布

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.

3条回答
Emotional °昔
2楼-- · 2019-04-07 22:04

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楼-- · 2019-04-07 22:05

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);
}
查看更多
放荡不羁爱自由
4楼-- · 2019-04-07 22:29

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.

查看更多
登录 后发表回答