asp.net-mvc 如何在 mvc4 中的特定视图中添加单个 css 文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12493116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:15:29  来源:igfitidea点击:

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

asp.net-mvcasp.net-mvc-4razor

提问by GotiBandhu Huda

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.

实际上我有一个母版页,我正在将此母版页添加到另一个视图 (Index.cshtml) 中,现在我想将另一个单独的 css 文件添加到 Index.cshtml 视图中。

回答by 360Airwalk

In the head section of your master page (e.g. _Layout.cshtml) add a RenderSection call. Your header section could look like this:

在您的母版页(例如 _Layout.cshtml)的头部部分添加一个 RenderSection 调用。您的标题部分可能如下所示:

<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:

然后在您的 Index.cshtml 中使用该部分添加您的 css 链接:

@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.

请注意,“css”是您的部分的唯一名称,它需要匹配。您还可以在您想要的任何视图中使用此部分。您在 css 部分中指定的部分将在 html 的 head-tag 中呈现,就在您将 RenderSection 占位符放入 _Layout.cshtml 的位置。

回答by CR41G14

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

不好的做法,但你可以只在视图顶部添加一个 html 链接标签或脚本标签,现代浏览器仍然会呈现它。它并不总是需要在母版页的头部

回答by Mihalis Bagos

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

您可以使用 Razor部分,或者一个字符串集合并将其存储在 ViewBag.CSS 中,然后在布局上渲染它,或者如果您不精通 razor 也可以使用 javascript

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