Greg Burghardt Greg Burghardt - 1 year ago 66
ASP.NET (C#) Question

How to include style sheet only on pages in a certain Area in ASP.NET MVC?

I have a style sheet that I only want included on web pages that are a part of a specific Area in MVC.

I know, by default, you get

Areas/<Area Name>/Views/_ViewStart.cshtml
, but I want the default layout rendered for this area. My Area's _ViewStart file looks like:

@ {
Layout = "~/Views/Shared/_Layout.cshtml";

I tried adding a call to
Styles.Render("My Bundle Name")
in the _ViewStart file for my Area, but the
tag is not showing up in the HTML source.

I even created an
extension method that returns the name of the current Area in MVC from the Route, and including the stylesheet that way:

@if (Html.AreaName() == "MyArea")

Code for the
extension method:

public static string AreaName<TModel>(this HtmlHelper<TModel> htmlHelper)
return htmlHelper.ViewContext.RouteData.Values["area"] as string;

But this always returns null. I even debugged the application and poked around the "Locals" debugger tab. The route data contains the controller, id and action name, but not the area name even though it's rendering a page in my area.


I am creating a NuGet package for this area that can be installed on any MVC application. In our organization, we are given a basic HTML and CSS layout based on Bootstrap, so there is some predictability with layout, but I'd like to hedge my bets and only import styles specific to my Area on pages rendered from that Area.

How can I include a style sheet for pages in one certain Area in MVC, that doesn't show up in other Areas, or pages with no Area?

Answer Source

You should read the area name from DataTokens

This should work.

public static string AreaName<TModel>(this HtmlHelper<TModel> htmlHelper)
    return htmlHelper.ViewContext.RouteData.DataTokens["area"] as string;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download