【问题标题】:Limit JavaScript and CSS files on ASP.NET MVC 2 Master Page based on Model and View content根据模型和视图内容限制 ASP.NET MVC 2 母版页上的 JavaScript 和 CSS 文件
【发布时间】:2010-05-20 21:18:24
【问题描述】:

我只想在需要它们的页面上包含某些 .js 和 .css 文件

例如,我的 EditorTemplate DateTime.ascx 需要文件 anytimec.jsanytimec.css

每当我在具有 DateTime 类型值的模型的视图中使用 EditorForEditorForModel 辅助方法时,都会应用该模板。

我的技巧:

我已将此条件放入我的母版页的<head> 部分。它检查 ModelMetadata 中的 DateTime 类型属性。

<% 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>
<% } %>

这有两个问题

  1. 如果我嵌套了 DateTime 类型的子模型,则会失败

  2. 由没有EditorForEditorForModel 方法的视图不必要地触发(例如:DisplayForModel

如何改进这项技术?

【问题讨论】:

标签: asp.net-mvc-2 master-pages editortemplates modelmetadata mvc-editor-templates


【解决方案1】:

就个人而言,我会使用局部视图和 ASP 内容占位符。

在 Views/Shared 中有一个部分视图 EditorScripts.ascx,其中包含定义要包含在编辑页面中的脚本的标签。

然后在 Site.Master &lt;head&gt; 标签中放置一个占位符,如下所示:

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

在您想要/需要脚本的任何视图中,输入以下代码:

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

这不是一个完美的解决方案,也不是您想要的那样动态。使用部分视图的原因是,如果您决定更新或向这些视图添加更多脚本,那么您只需在一个位置进行更新。

另一种方法是拥有一个包含这些脚本和其他编辑器特定内容的Editor.Master 页面,然后让该主使用Site.Master 作为它的母版页。然后所有编辑器视图都将Editor.Master 作为其母版页。

HTH

【讨论】:

    【解决方案2】:

    我认为telerik web asset manager 可以让你完成你想要的并且是开源的。

    【讨论】:

      猜你喜欢
      • 2011-02-20
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多