Limit JavaScript and CSS files on the ASP.NET MVC 2 home page based on model and view content

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

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

This template applies whenever I use EditorFor or EditorForModel in a model view with a value of type DateTime.

My technique:

I placed this condition in the <head> section of my main page. It checks a property of type DateTime in 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 :

How can I improve this technique?

0
asp.net-mvc-2 master-pages mvc-editor-templates
source share
2 answers

Personally, I would use a partial view and ASP Content Placeholder.

Views / Shared has a partial view of EditorScripts.ascx that contains tags that define the scripts that will be included in your editing pages.

Then place the placeholder in the Site.Master <head> , something like this:

 <asp:ContentPlaceHolder ID="HeadContent" runat="server" /> 

In any view you want / need scripts, enter this code:

 <asp:Content ContentPlaceHolderID="HeadContent" runat="server"> <% Html.RenderPartial("EditorScripts"); %> </asp:Content> 

This is not an ideal solution and not as dynamic as we would like. The reason for using a partial view is that if you decide to update or add more scripts for these views, you only need to update them in one place.

Another way would be to have an Editor.Master page containing these scripts and other editor-specific topics, then this wizard uses Site.Master as the main page. Then all editor views will have Editor.Master as the main page.

NTN

+1
source share

I think the telerik web resource manager allows you to accomplish what you want and is open source.

+1
source share

All Articles