Dario - 由于将其用于部分视图,您将始终遇到文档的 <head> 部分已就位,因此无法修改的问题。如果您想保持 WC3 兼容,那么您必须通过 javascript 将任何进一步的 css 放入 head 部分。这可能是可取的,也可能不是可取的(如果您必须在关闭 javascript 的情况下满足下游浏览器的需求)。
您可能会想到的主要问题是您不能将<asp:contentplaceholders> 放入您的部分。这很痛苦(虽然母版页引用会将部分内容与特定母版页联系得太紧密,但这是可以理解的)。
为此,我创建了一个小助手方法,它可以完成基本的繁重工作以自动将 css 文件放入 head 部分。
edit - (根据 Omu 的 js 建议)这是一个不错的中途小屋:
// standard method - renders as defined in as(cp)x file
public static string Css(this HtmlHelper html, string path)
{
return html.Css(path, false);
}
// override - to allow javascript to put css in head
public static string Css(this HtmlHelper html, string path, bool renderAsAjax)
{
var filePath = VirtualPathUtility.ToAbsolute(path);
HttpContextBase context = html.ViewContext.HttpContext;
// don't add the file if it's already there
if (context.Items.Contains(filePath))
return "";
// otherwise, add it to the context and put on page
// this of course only works for items going in via the current
// request and by this method
context.Items.Add(filePath, filePath);
// js and css function strings
const string jsHead = "<script type='text/javascript'>";
const string jsFoot = "</script>";
const string jsFunctionStt = "$(function(){";
const string jsFunctionEnd = "});";
string linkText = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\"></link>", filePath);
string jsBody = string.Format("$('head').prepend('{0}');", linkText);
var sb = new StringBuilder();
if (renderAsAjax)
{
// join it all up now
sb.Append(jsHead);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionStt);
sb.AppendFormat("\r\n\t\t");
sb.Append(jsBody);
sb.AppendFormat("\r\n\t");
sb.Append(jsFunctionEnd);
sb.AppendFormat("\r\n");
sb.Append(jsFoot);
}
else
{
sb.Append(linkText);
}
return sb.ToString();
}
用法:
<%=Html.Css("~/Content/yourstyle.Css")%>
或:
<%=Html.Css("~/Content/yourstyle.Css", true)%> // or false if you want!!
如果所有其他方法都失败了,则值得采取自负盈亏的方法。也可以调整上面的逻辑来点击 actionfilter 并将 css 添加到响应头等中,而不是输出 js 字符串。