Friday, October 26, 2012

Razor @Sections, Javascript and the conundrum of EditorTemplates

With the exception of when using Modernizr I always try to adhere to the web performance rules of css at the top of the page and javascript at the bottom. The razor @RenderSection(string name, bool required) helper class and the @Section keyword certainly helps with that goal within view pages.

I recently came across this problem in a project for partial views. For instance if I create a DateTime.cshtml to represent an EditorTemplate for DateTime properties on View Models. I can't just inject the relevant scripts for the jQuery UI Date picker extension using the @section Scripts method like you can do within normal views.

So how can a developer adhere to best practices for stylesheets and script files? By using an extension method.

Let's start with adding a couple of extension methods, Resource and RenderResources as described below.

As you can see the Resource method takes a signature of Func<object, dynamic> template which simply can be @ so when template is executed the script tag is written into the page. The other parameter type is the type of resource being rendered "css" or "js", I've created a static helper class to remove the magic string.


In the layout:


In the partial :


I haven't tested with Asp .net bundle as yet but with little or no tweaking that should work as well.