在不影响调试能力的情况下解决此问题的另一种选择可能是:
public static IHtmlString Render(string path, IDictionary<string, object> htmlAttributes)
{
var attributes = BuildHtmlStringFrom(htmlAttributes);
#if DEBUG
var originalHtml = Styles.Render(path).ToHtmlString();
string tagsWithAttributes = originalHtml.Replace("/>", attributes + "/>");
return MvcHtmlString.Create(tagsWithAttributes);
#endif
string tagWithAttribute = string.Format(
"<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\"{1} />",
Styles.Url(path), attributes);
return MvcHtmlString.Create(tagWithAttribute);
}
我正在做的只是将给定的 html 属性附加到标签的末尾(在调试模式下)或唯一的链接标签的末尾(启用缩小/捆绑时)。
视图中的用法:
@Bundles.Render("~/css/print", new { media = "print" })
其余代码:
public static IHtmlString Render(string path, object htmlAttributes)
{
return Render(path, new RouteValueDictionary(htmlAttributes));
}
private static string BuildHtmlStringFrom(IEnumerable<KeyValuePair<string, object>> htmlAttributes)
{
var builder = new StringBuilder();
foreach (var attribute in htmlAttributes)
{
builder.AppendFormat(" {0}=\"{1}\"", attribute.Key, attribute.Value);
}
return builder.ToString();
}
我写了一篇关于这个主题的博客文章:http: //danielcorreia.net/blog/quick-start-to-mvc4-bundling/