开发者

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

I want to include certain .js and .css files only on pa开发者_JAVA技巧ges 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:

  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?


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

In the Views/Shared have a partial view EditorScripts.ascx which contains the tags defining the scripts to be included in your editing pages.

Then put a placeholder in the Site.Master <head> tag, something like this:

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

The, in any view that you want/need the scripts, put this code:

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

This isn't a perfect solution and isn't as dynamic as you would like. The reason for using a partial view is that if you decide to update or add more scripts to those views, then you only have to update it in one location.

Another way would be to have a Editor.Master page that contains these scripts and other editor specific things then have that master use the Site.Master as it's master page. Then all editor views would have the Editor.Master as their master page.

HTH


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜