是的!我在更新的问题中链接的帖子是正确的!这是解决方案:
public static class ResourceCombiningHelper
{
private static string MakeKey(string type)
{
return "CombinableResource" + (type ?? "").ToLowerInvariant();
}
public static IHtmlString CombinableResource(this HtmlHelper helper, dynamic template, string type)
{
var key = MakeKey(type);
var context = helper.ViewContext.HttpContext;
var resources = (List<dynamic>)context.Items[key];
if (resources == null)
{
resources = new List<dynamic> { template };
context.Items[key] = resources;
}
else
{
resources.Add(template);
}
return new HtmlString(String.Empty);
}
public static IHtmlString RenderCombinableResources(this HtmlHelper helper, string type)
{
var key = MakeKey(type);
var context = helper.ViewContext.HttpContext;
var resources = (List<dynamic>)context.Items[key];
if (resources != null)
{
foreach (var resource in resources)
{
if (resource is HelperResult)
{
// Add in-line content to combined resource here.
}
else if (resource is string)
{
// Add external reference to combined resource here.
}
}
}
// Return a single reference to the combined resource (<link>, <script>, etc.)
}
}
Razor 视图中的用法:
@helper ColorOverridingStyle(string color)
{
<style type="text/css">
* { color: @color; }
</style>
}
@{ var color = ViewBag.TextColor; }
@Html.CombinableResource(Url.Content("~/Content/site.css"), "css")
@Html.CombinableResource(Url.Content("~/Content/menu.js"), "js")
@Html.CombinableResource(ColorOverridingStyle(color), "css")
最后的 HTML 输出示例:
<head>
<link href="/Content/combined-css.css" rel="stylesheet" type="text/css" />
<script src="/Content/combined-js.js" type="text/javascript"></script>
</head>
效果很好!去扩展这个小宝石的极限...... :)