Conditionally, including stylesheets in the layout depending on the name of the controller

I am learning ASP.NET MVC 3 Framework. On my layout page ( _Layout.cshtml), I would like to conditionally include some CSS stylesheets depending on the name of the controller. How to do it?

+3
source share
4 answers

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()
+5
source

I would use a different approach. Define the base controller and define the SetStyleSheet method, for example:

public abstract class BaseController : Controller
{
    protected override void Intialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        SetStyleSheet();
    }

    protected virtual void SetStyleSheet()
    { }
}

SetStyleSheet, - ViewData["styleSheet"] , , (_Layout.cshtml).

+2

, HTML , , CSS .

<body id="<%=ViewContext.RouteData.GetRequiredString("controller").ToLower() %>">
    ... content here
</body>
+1

ControllerContext, ViewContext - aleady, , .

:

public static class ControllerContextExtensions
{
    public static string GetControllerName(this ControllerContext helper)
    {
        if (helper.Controller == null)
        {
            return string.Empty;
        }

        string[] fullControllerNames = helper.Controller.ToString().Split('.');

        return fullControllerNames[fullControllerNames.Length-1].Replace("Controller",string.Empty);
    }

}

_Layout:

@if(ViewContext.GetControllerName() == "MyControllerName")
{
  //load my css here
}

bool.

0

All Articles