Keeping everything tidy within ASP.NET MVC3 C#; rendering your CSS and JavaScripts in the correct place
Nothing annoys me more than looking at a websites source code and seeing a big huge mess. Incorrect indentation, no standardization, incorrect HTML tags, and my biggest gripe: CSS/JavaScript files in the wrong place.
I can cope with the indentation as you may want to squeeze out those last few bytes from the white space if you have high-traffic website but please put your JavaScript files just before your closing body tag. If you put your JS files in your head tag then you potentially run the risk of holding up the rest of your website because loading these files is blocking, i.e. synchronous. Anyhow, to get to my point in MVC2 or MVC3 you would probably normally use Content tags or Razors @section { } blocks, which is fine until you need to dynamically load JS and CSS files in partial views where these blocks just don’t work. You could just write the script tag statically but then it would appear half way down the page thus I propose these two helpers (MVC3):
public static IHtmlString Resource(this HtmlHelper HtmlHelper, Func<object, HelperResult> Template, string Type)
{
if (HtmlHelper.ViewContext.HttpContext.Items[Type] != null) ((List<Func<object, HelperResult>>)HtmlHelper.ViewContext.HttpContext.Items[Type]).Add(Template);
else HtmlHelper.ViewContext.HttpContext.Items[Type] = new List<Func<object, HelperResult>>() { Template };
return new HtmlString(String.Empty);
}
public static IHtmlString RenderResources(this HtmlHelper HtmlHelper, string Type)
{
if (HtmlHelper.ViewContext.HttpContext.Items[Type] != null)
{
List<Func<object, HelperResult>> Resources = (List<Func<object, HelperResult>>)HtmlHelper.ViewContext.HttpContext.Items[Type];
foreach (var Resource in Resources)
{
if (Resource != null) HtmlHelper.ViewContext.Writer.Write(Resource(null));
}
}
return new HtmlString(String.Empty);
}
Then in any of your views you can do @Html.Resource(@<script … />, “js”) and @Html.RenderResources(“js”) just before your closing body tag – it works in partial views too!
Related posts:
- Introducing PubNub – the new cloud-hosted service for real-time messaging
- My New Open-Source Project, SimpleForum

