基于模型和视图内容限制 ASP.NET MVC 2 母版页上的 JavaScript 和 CSS 文件
我想仅在需要的页面上包含某些 .js 和 .css 文件。
例如,我的 EditorTemplate DateTime.ascx
需要文件 anytimec.js
和 anytimec.css
。
每当我使用 EditorFor< 时,都会应用该模板/a> 或 EditorForModel 辅助方法在具有 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>
<% } %>
这有两个问题:
如果我嵌套了 DateTime 类型的子模型,则失败
由没有 EditorFor 或 EditorForModel 方法(示例:DisplayForModel)
由
如何改进这项技术?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
就个人而言,我会使用部分视图和 ASP 内容占位符。
在视图/共享中有一个部分视图
EditorScripts.ascx
,其中包含定义要包含在编辑页面中的脚本的标签。然后在 Site.Master
标记中放置一个占位符,如下所示:
在您想要/需要脚本的任何视图中,放置此代码:
这不是一个完美的解决方案并且没有您想要的那么动态。使用部分视图的原因是,如果您决定更新或向这些视图添加更多脚本,则只需在一个位置进行更新。
另一种方法是拥有一个包含这些脚本和其他编辑器特定内容的
Editor.Master
页面,然后让该母版使用Site.Master
作为其母版页。然后,所有编辑器视图都将Editor.Master
作为其母版页。华泰
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:The, in any view that you want/need the scripts, put this code:
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 theSite.Master
as it's master page. Then all editor views would have theEditor.Master
as their master page.HTH
我认为 telerik Web 资产管理器 允许您完成你想要的并且是开源的。
I think the telerik web asset manager allows you to accomplish what you want and is open source.