Limit JavaScript and CSS files on ASP.NET MVC 2 Master Page based on Model and View content

Posted by Zack Peterson on Stack Overflow See other posts from Stack Overflow or by Zack Peterson
Published on 2010-05-20T21:18:24Z Indexed on 2010/05/20 21:20 UTC
Read the original article Hit count: 281

I want to include certain .js and .css files only on pages that need them.

For example, my EditorTemplate DateTime.ascx needs files anytimec.js and anytimec.css.

That template is applied whenever I use either the EditorFor or EditorForModel helper methods in a view for a model with a DateTime type value.

I've put this condition into the <head> section of my master page. It checks for a DateTime type property in the ModelMetadata.

<% if (this.ViewData.ModelMetadata.Properties.Any(p => p.ModelType == typeof(DateTime))) { %>
    <link href="../../Content/anytimec.css" rel="stylesheet" type="text/css" />
    <script src="../../Scripts/anytimec.js" type="text/javascript"></script>
<% } %>

This has two problems:

  1. Fails if I have nested child models of type DateTime

  2. Unnecessarily triggered by views without EditorFor or EditorForModel methods (example: DisplayForModel)

How can I improve this technique?

© Stack Overflow or respective owner

Related posts about asp.net-mvc-2

Related posts about editortemplates