.NET MVC Razor - 作用域样式

.NET MVC Razor - Scoped Styles

目前我正在尝试在我的其中一个视图中使用部分视图,该视图使用 不同 css 样式 sheet。但是,由于 Razor 中样式呈现的方式,主视图中的样式被继承: @Styles.Render("~/Content/css") 简单地适用于所有内容,而且我似乎无法在中找到任何关于作用域 css 的文档剃刀.

执行以下代码不起作用 - 我相信是因为 Razor 通过简单地放置在头部来处理 Styles.Render。

<div>
    <style scoped>
        @Styles.Render("~/Content/othercss")
    </style>
    @Html.Partial("~\Views\Layouts\blog.cshtml")
</div>

有人知道解决这个问题的方法吗?

Styles.Render() 为浏览器呈现 link 标签以获取 CSS 文件,如下所示:

<link rel="stylesheet" type="text/css" href="https://whatever.css">

这不是 style 元素中的预期内容。你想要做什么输出那个 CSS 文件的内容,例如:

<style scoped>
    @Html.Raw(File.ReadAllText(Server.MapPath("~/Content/yourfile.css")))
</style>

请注意,这不是在使用您的包,为此您需要访问包并以某种方式呈现它(超出此答案的范围)。

说了这么多,请注意 scoped 属性的 docs 是这样说的:

Non-standard This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behaviour my change in the future.

Obsolete This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

更好的选择是首先确定 CSS 的范围。例如:

div#wrapper .red {
    background-color: red;
}

现在这种风格只适用于 ID 为 wrapperdiv 内部。答:如果你把你的 CSS 写成 SASS 之类的(你 真的 应该是!),那就更简单了:

div#wrapper {

    .red {
        background-color: red;
    }
    .some-other-style {
        display: block
    }
}