How can I add contents of an external file to my Razor MVC3 layout file
I have the following code in my _Layout:
@if (ViewBag.PageFormat == "Footer Buttons")
{
}
If I pass the "Footer Buttons" string in the viewbag then I would like to insert CSS code from an external file directly into the cshtml file. Something like an 开发者_运维百科insert of the contents of an external file right into the cshtml file between the { and }.
Is there a way I can do this with MVC3?
If you mean load up CSS from an external file as inline CSS code, you should create an extension method on your HtmlHelper.
public static class CssHelper
{
public static MvcHtmlString LoadCss(this HtmlHelper html, string file)
{
string css = System.IO.File.ReadAllText(html.ViewContext.HttpContext.Server.MapPath(file));
TagBuilder styleTag = new TagBuilder("style");
styleTag.Attributes["type"] = "text/css";
styleTag.InnerHtml = css;
return MvcHtmlString.Create(styleTag.ToString());
}
}
which you can call in your code like this:
@if (ViewBag.PageFormat == "Footer Buttons")
{
@Html.LoadCss("~/Content/mycss.css");
}
精彩评论