Too many JavaScript and CSS files on my ASP.NET MVC 2 Master Page?

喜欢而已 提交于 2019-12-30 11:41:29

问题


I'm using an EditorTemplate DateTime.ascx in my ASP.NET MVC 2 project.

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%: Html.TextBox(String.Empty, Model.ToString("M/dd/yyyy h:mm tt")) %>
<script type="text/javascript">
    $(function () {
        $('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty) %>').AnyTime_picker({
            format: "%c/%d/%Y %l:%i %p"
        });
    });
</script>

This uses the Any+Time™ JavaScript library for jQuery by Andrew M. Andrews III.

I've added those library files (anytimec.js and anytimec.css) to the <head> section of my master page.

Rather than include these JavaScript and Cascading Style Sheet files on every page of my web site, how can I instead include the .js and .css files only on pages that need them--pages that edit a DateTime type value?


回答1:


First idea that comes to mind =>

Template:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%: Html.TextBox(String.Empty, Model.ToString("M/dd/yyyy h:mm tt")) %>
<script type="text/javascript">
    $(function () {
        MakeSureAnyTimeIsIncluded();
        $('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty) %>').AnyTime_picker({
            format: "%c/%d/%Y %l:%i %p"
        });
    });
</script>

masterpage or shared external JS file:

  function MakeSureAnyTimeIsIncluded(){
    if (!anyTimeIsIncluded)
      //document.write(<script src="correct url") something like that
      anyTimeIsIncluded=true;
  }



回答2:


In your master:

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

And in the Views (aspx) that will use the EditorTemplate/plugin:

<asp:Content ID="indexScripts" ContentPlaceHolderID="Scripts" runat="server">
    <script type="text/javascript" src="anytime.js"></script>
</asp:Content>


来源:https://stackoverflow.com/questions/2852928/too-many-javascript-and-css-files-on-my-asp-net-mvc-2-master-page

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