samedi 5 mai 2012

CSS and javascript links with Razor

Problem
I've recently started work on an ASP.Net MVC project and I am using Razor as the view engine. So far I really like it, compared to the default view engine, the syntax is far cleaner and more concise.  However one of the issues I have come across is the need to add CSS links to a web page. Unlike a javascript link which can be placed anywhere in the body of an HTML page CSS links always need to be added in the <head> section of an HTML page which we do not have access to in a child page. . What to do?

Solution
In VS2010 with each new Razor MVC project a _Layout.cshtml page is included in the Views/Shared folder, this is the Razor equivalent of a master page. In addition there is a dynamic data dictionary called the ViewBag which can be accessed by a controller or view.My first thought was to use the ViewBag to define a collection of links which could then be rendered in the _layout.cshtml page. This, however, would have been pretty clunky and semantically not very pretty. A while later I read an article about sections in Razor and realized that these very powerful constructs would be perfect for this scenario!


<head>
    <title>@ViewBag.Title</title>
    <link href="http://c-lien.blogspot.com/?QFVybC5Db250ZW50KA=="~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
    @RenderSection("head",false)
</head>


The important bit to note here is the addition of the @RenderSection method which will then cause any code that you created in a "head" section of a child page to be rendered here. It takes a parameter indicating whether every child page need to define the section in question or not, by default this parameter is set to true, I have set it to false as not every child page will have to define extra head content. 

The code that was added to the child page looks as follows:

@section Head
{
    <link href="http://c-lien.blogspot.com/?QFVybC5Db250ZW50KA=="~/Content/datePicker.css")" rel="stylesheet" type="text/css" />
}


Razor keeps on with the easy to use fluid syntax by allowing you to declare which section you are defining content for by simply writing @section and the name of the section. Nice! You can now add any content css links, javascript links, etc to your web page simply and easily.


CSS links in Razor - done!

I have also blogged on how to easily switch between different versions of javascript files here

Edit 27 Oct 2010
A number of readers commented that they were getting an error stating "element link cannot be nested within element link", I personally haven't experienced this issue so I suggest trying a complete rebuild of your project if you do encounter it. Otherwise another reader has suggested you can get around it by switching the "Target Schema for Validation" to HTML5.

Aucun commentaire:

Enregistrer un commentaire