You can get the name of the current controller using the following property:
ViewContext.RouteData.GetRequiredString("controller")
Thus, based on its value, you can enable or disable the stylesheet:
@if (ViewContext.RouteData.GetRequiredString("controller") == "somecontrollername")
{
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
}
Or use a custom helper:
public static class CssExtensions
{
public static IHtmlString MyCss(this HtmlHelper html)
{
var currentController = html.ViewContext.RouteData.GetRequiredString("controller");
if (currentController != "somecontrollername")
{
return MvcHtmlString.Empty;
}
var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
var link = new TagBuilder("link");
link.Attributes["rel"] = "stylesheet";
link.Attributes["type"] = "text/css";
link.Attributes["href"] = urlHelper.Content("~/Content/Site.css");
return MvcHtmlString.Create(link.ToString(TagRenderMode.SelfClosing));
}
}
and in the layout just:
@Html.MyCss()
source
share