2012-07-25

Dynamic CSS

Today I was in need of changing the css file for some pages in a MVC3 project.
Still I want to keep the layout page with a default css (overwritten in case there is another one for that page)
I've read several complex solutions, but then I thought: "that can't be right"
I mean, it is something too simple to use a whole nuget for that.

Did some tests, and it worked.
There are only 2 simple steps.

1: change your _layout page to this:

<link href="@Url.Content(ViewBag.Css ?? "~/Content/Site.css")" rel="stylesheet" type="text/css" />

2: in the pages you want to change the css files, simply do

ViewBag.Css = "~/Content/OtherSite.css";

Easy, right?
Enjoy