How to add individual css file in particular view in mvc4?

。_饼干妹妹 提交于 2019-12-21 16:18:13

问题


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);
}


来源:https://stackoverflow.com/questions/12493116/how-to-add-individual-css-file-in-particular-view-in-mvc4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!