我有一个问题,我试图拥有一个默认的 CSS 页面,但根据某些方面可以更改其 CSS。一群人可以通过数据库条目将他们的 CSS 更改为他们自己的自定义版本,他们发布一个长字符串,其中包含 CSS 需要设置的内容。但是,他们也可以做一些简单的事情,只是想覆盖背景或整个网站。
<head>
<link href="/static/css/styles.css" rel="stylesheet" />
<style type="text/css">
@{
WebExtensionHelper.CustomCSS();
}
</style>
</head>
WebExtensionHelper.CustomCSS() 返回一个包含所有 CSS 的字符串,如前所述。我需要它来影响每个页面,所以我需要在 _Layout.cshtml 页面上使用它。另一件要考虑的事情是否有帮助,我将有大约 200 个人想要 customcss。
最佳答案
一种解决方案是在运行时生成自定义 CSS 文件。在您的布局中,您可以将样式表链接指向 Controller 操作而不是实际文件:
<link href="@Url.Action("Index", "Style", new { whichStyle = myValue })" rel="stylesheet" type="text/css" />
在 Style Controller 中,创建一个 Index 方法:
public ActionResult Index(string whichStyle)
{
MyStyleViewModel model = new MyStyleViewModel();
// -- (Load relevant style settings here) --
Response.ContentType = "text/css";
return View(model);
}
然后在 Index View 中,正常写出 css:
@model MyStyleViewModel
@{ Layout = null; }
body
{
color:#333;
@if (Model.Font == "Lucida")
{
@:font-family:"Lucida Grande", sans-serif;
}
else
{
@:font-family:Georgia, Serif;
}
}
我没有运行那个确切的 View 代码,因此请根据您的情况进行调整。
关于c# - MVC 4 _Layout.cshtml 动态 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16678688/