これは古い質問だと思いますが、バンドルを埋め込むdprotheroの回答の修正版を次に示します。静的 C# クラスを作成し、このメソッドをその中に入れます。
public static IHtmlString EmbedCss(this HtmlHelper htmlHelper, string path)
{
try
{
// Get files from bundle
StyleBundle b = (StyleBundle)BundleTable.Bundles.GetBundleFor("~/Content/css");
BundleContext bc = new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, "~/Content/css");
List<BundleFile> files = b.EnumerateFiles(bc).ToList();
// Create string to return
string stylestring = "";
// Iterate files in bundle
foreach(BundleFile file in files)
{
// Get full path to file
string filepath = HttpContext.Current.Server.MapPath(file.IncludedVirtualPath);
// Read file text and append to style string
string filetext = File.ReadAllText(filepath);
stylestring += $"<!-- Style for {file.IncludedVirtualPath} -->\n<style>\n{filetext}\n</style>\n";
}
return htmlHelper.Raw(stylestring);
}
catch
{
// return nothing if we can't read the file for any reason
return null;
}
次に、それを使用したいビューに移動します。ビューに CSS ヘルパーが表示されるように、必ず using ステートメントを追加してください。また、TempData を使用して、インラインでレンダリングするかどうかを決定します。
<!-- Using statement -->
@using Namespace.Helpers;
<!-- Check tempdata flag for whether or not to render inline -->
@if (TempData["inlinecss"] != null)
{
<!-- Embed CSS with custom code -->
@Html.EmbedCss("~/Content/css")
}
else
{
<!-- Use links to reference CSS -->
@Styles.Render("~/Content/css")
}