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.
My technique:
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:
Fails if I have nested child models of type DateTime
Unnecessarily triggered by views without EditorFor or EditorForModel methods (example: DisplayForModel)
How can I improve this technique?