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

佐手、 提交于 2019-12-11 14:08:24

问题


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:

  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?


回答1:


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




回答2:


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



来源:https://stackoverflow.com/questions/2877927/limit-javascript-and-css-files-on-asp-net-mvc-2-master-page-based-on-model-and-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!