1

This has been asked before, but nobody responded, so I ask again as I feel it is important.

Unobtrusive validation for web forms works great, but, only when validation controls are added to a form. For other pages that lack validation controls, no reference to the JQuery file is rendered.

I currently use JQuery on all pages, so reference it manually in a Master page file,

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

The problem is that when I access a page with my own JQuery logic and validation controls, then two references get created (my own, plus ASP.Net's ScriptResourceDefinition).

How can I achieve one of the following:

  1. Let ScriptResourceDefinition know that the file exists and has already been added?
  2. Force ScriptResourceDefinition to render JQuery on every page regardless of whether it detects validation controls?
Community
  • 1
  • 1
EvilDr
  • 8,943
  • 14
  • 73
  • 133

1 Answers1

2

Found the answer here https://stackoverflow.com/a/12628170/792888

The answer is to inherit from ScriptManager and stop ASP.Net's built-in behaviour of creating the unnecessary (duplicate) JQuery link

using System;
using System.Linq;
using System.Web.UI;

namespace WebApplication46
{
    public class CustomScriptManager : ScriptManager
    {
        protected override void OnInit(EventArgs e)
        {
            Page.PreRenderComplete += Page_PreRenderComplete;
            base.OnInit(e);
        }

        private void Page_PreRenderComplete(object sender, EventArgs e)
        {
            var jqueryReferences = Scripts.Where(s => s.Name.Equals("jquery", StringComparison.OrdinalIgnoreCase)).ToList();
            if (jqueryReferences.Count > 0)
            {
                // Remove the jquery references as we're rendering it manually in the master page <head>
                foreach (var reference in jqueryReferences)
                {
                    Scripts.Remove(reference);
                }
            }
        }
    }
}

In web.config this is wired up to replace the standard ScriptManager:

<system.web>
  <pages>
    <tagMapping>
      <add tagType="System.Web.UI.ScriptManager" mappedTagType="WebApplication46.CustomScriptManager" />
    </tagMapping>
  </pages>
</system.web>
Community
  • 1
  • 1
EvilDr
  • 8,943
  • 14
  • 73
  • 133