如何在mvc4中的特定视图中添加单个css文件?

Got*_*uda 6 asp.net-mvc razor asp.net-mvc-4

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

360*_*alk 24

在母版页的head部分(例如_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>
Run Code Online (Sandbox Code Playgroud)

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

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

请注意,"css"是您的部分的唯一名称,需要匹配.您也可以在任何所需的视图中使用此部分.然后,您在css部分中指定的部分将在html的head-tag中呈现,就像您将RenderSection占位符放在_Layout.cshtml中一样.


Mih*_*gos 0

您可以使用 Razorsections字符串集合并将其存储在 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);
}
Run Code Online (Sandbox Code Playgroud)