I am learning the ASP.NET MVC 3 Framework. In my layout page (_Layout.cshtml
), I would like to conditionally include some CSS stylesheets depending on the name of the controller. How do I do that?
The _ViewStart. cshtml page is a special view page containing the statement declaration to include the Layout page. Instead of declaring the Layout page in every view page, we can use the _ViewStart page. When a View Page Start is running, the “_ViewStart. cshtml” page will assign the Layout page for it.
In ASP.NET Web Pages, you can define a layout page that provides an overall container for pages on your site. For example, the layout page can contain the header, navigation area, and footer. The layout page includes a placeholder where the main content goes.
The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.
You could obtain the current controller name using the following property:
ViewContext.RouteData.GetRequiredString("controller")
So based on its value you could include or not 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 layout simply:
@Html.MyCss()
I would use different approach. Define base controller instead and define method SetStyleSheet like:
public abstract class BaseController : Controller
{
protected override void Intialize(RequestContext requestContext)
{
base.Initialize(requestContext);
SetStyleSheet();
}
protected virtual void SetStyleSheet()
{ }
}
In derived classes you can override SetStyleSheet
to set something like ViewData["styleSheet"]
and use it for example in your master page (_Layout.cshtml).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With