Using jQuery with ASP.NET Master Page

Posted by: Suprotim Agarwal , on 3/13/2011, in Category jQuery and ASP.NET
Views: 325985
Abstract: jQuery has gained popularity as the de facto standard for JavaScript development and many ASP.NET developers have adopted jQuery as part of their development kits. One question that I am asked frequently is how to use jQuery with an ASP.NET Master Page. Let us see how.

jQuery has gained popularity as the de facto standard for JavaScript development and many ASP.NET developers have adopted jQuery as part of their development kits. One question that I am asked frequently is how to use jQuery with an ASP.NET Master Page. Where should the jQuery file and code be placed in a Master Page?

Note: If you are using jQuery with ASP.NET Controls, check out my EBook called 51 Recipes with jQuery and ASP.NET Controls.

In this article, I am going to answer these questions and will demonstrate how to use jQuery with an ASP.NET MasterPage. We will see some jQuery code that clones the content of one TextBox into another TextBox. If you are new to jQuery, check my article Using jQuery with ASP.NET – Beginner’s Guide.

Let’s get started.

Step 1: Create a Master Page (MasterPage.master) and add a reference to the jQuery Library. Now create a folder called ‘Scripts’ and download the latest jQuery library into this folder. Now add references to any CSS files, if any. Create a separate folder to store all CSS and images files. You should always make it a habit to keep your resources in separate folders for better maintainability. The code should look similar to the following:

Step 2: Now create a Content Page called ‘Default.aspx’ and add two TextBox controls to this page as shown below:

Step 3: Now in the ‘Scripts’ folder, create a textboxclone.js file and add the following code in it.

Using the code shown above, as the user types in the first TextBox, we retrieve the value of the first TextBox and set it to the value of the second TextBox. Note: Since we are capturing the keyup event, whenever the user pastes text in the first textbox using Ctrl+v, the contents are cloned into the second textbox, This is however not true when the user right clicks the textbox and chooses paste from the context menu

The last step is to reference this JavaScript file (textboxclone.js) in your Content Page as shown below:

You must be wondering why did we add a link to the textboxclone.js from a Content page rather than doing it from a Master Page. The reason is, if we had referenced the textboxclone.js file in the MasterPage directly, the code would be downloaded for every content page, even if it was not needed. Referencing it from a Content Page makes sure that the resource is used only when this content page is requested. That’s it. Run the code and you will see the textbox text cloning in action.

I hope you liked this article and I thank you for viewing it.

The entire source code of this article can be downloaded over here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Anthony on Sunday, March 13, 2011 7:04 AM
Alternatively, just create a separate master page with the script references for that particular page...
Comment posted by Brandon on Monday, March 14, 2011 2:06 AM
I am a regular reader of your site and I must say you have a good blend of dotnet topics for beginner, intermediate (like me) and advanced devs. Keep up the good work Dotnetcurry!
Comment posted by Suprotim Agarwal on Tuesday, March 15, 2011 5:51 AM
Brandon: Thanks for the feedback!
Comment posted by Prachi Chandrakar on Thursday, June 2, 2011 3:35 AM
Excellent article. Helped me a lot. Thank you very much.
Would you please join my discussion at C# Developers / Architects group at Linkedin.Actually I have a question and I've posted it there with the code.I'll appreciate.
Comment posted by berto on Friday, December 23, 2011 6:19 AM
Hello,
This works perfectly if default.asp is in the same directory. What if you create catalog def and put there default.asp. In this case it does not see js files from master page (path not correct). I tested ~/Scripts but it as well does not work. How can I solve this issue without moving asp file to main directory nor to create second master file?
Comment posted by Ophelia on Sunday, February 12, 2012 4:29 AM
Hey berto use this on your jQuery links. eg: <script type="text/javascript" src="<%=ResolveClientUrl("~/scripts/jquery-1.7.1.min.js")%>"></script> and it will work perfect!
Comment posted by Anup on Sunday, April 15, 2012 9:01 AM
ORA-12154:TNS:Could Not Resolve The Connect Identifier Specified.


My System Power:
64 Bit Operating System Windows 7 Home Basic,
6 GB RAM, Intel i3 Second Genaration.

Im always getting this kind of error while connecting from Visual Studio 2010 to the Oracle 10g database.


Reply Soon

Anup
Comment posted by Virendra Dugar on Friday, June 1, 2012 1:09 AM
Found a good article "Things to remember while using jQuery with ASP.NET Master Pages"

http://jquerybyexample.blogspot.com/2012/05/things-to-remember-while-using-jquery.html
Comment posted by Ranga on Monday, June 25, 2012 6:44 AM
Thank You  Suprotim Agarwal .But What to do for nested Masterpage.where there wont be head ContentPlaceHolder.Pls reply...
Comment posted by yogendra singh on Friday, August 10, 2012 3:37 PM
please give an example to repeat images alternatively
Comment posted by anony on Tuesday, August 28, 2012 1:52 AM
THANK you very much!!!
Comment posted by anish kumar dubey on Monday, March 4, 2013 7:51 AM
as i am beginner in jquery very usefull code for me
Comment posted by Martin Mbonu on Tuesday, March 26, 2013 12:39 PM
Really keep up the good work. You really touch the topics bothering most developers. Well done
Comment posted by kassthi rayan on Friday, April 5, 2013 7:14 AM
good work
Comment posted by Aditya Singh on Friday, June 21, 2013 2:10 AM
Gret Work
Comment posted by kavoshkar on Monday, June 24, 2013 3:43 PM
hi
that is good .thanks for help me
i have a nested master page and make webpage use inherited of nested master page
example: parentmasterpage/childmasterpage :
my page inherited from childmasterpage
i want to show a modal dialog div in webpage but it dosent work. in a page with out masterpage it work correctly but with master dose not.
my correct single page code is:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ParentForm.aspx.cs" Inherits="DivDialog.ParentForm" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body { font-size: 62.5%; }
      label, input { display:block; }
      input.text { margin-bottom:12px; width:95%; padding: .4em; }
      fieldset { padding:0; border:0; margin-top:25px; }
      h1 { font-size: 1.2em; margin: .6em 0; }
      div#users-contain { width: 350px; margin: 20px 0; }
      div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
      div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
      .ui-dialog .ui-state-error { padding: .3em; }
      .validateTips { border: 1px solid transparent; padding: 0.3em; }
    </style>

    
    <script src="../js/popup/jquery-1.9.1.js" type="text/javascript"></script>
    <link href="../js/popup/jquery-ui.css" rel="stylesheet" type="text/css" />
    <script src="../js/popup/jquery-ui.js" type="text/javascript"></script>
    <link href="../js/popup/jquery-ui.min.css" rel="stylesheet" type="text/css" />
    <link href="../js/popup/jquery.ui.theme.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
     $(function () {
         var name = $("#name"),
      email = $("#email"),
      password = $("#password"),
      allFields = $([]).add(name).add(email).add(password),
      tips = $(".validateTips");

         function updateTips(t) {
             tips
        .text(t)
        .addClass("ui-state-highlight");
             setTimeout(function () {
                 tips.removeClass("ui-state-highlight", 1500);
             }, 500);
         }

         function checkLength(o, n, min, max) {
             if (o.val().length > max || o.val().length < min) {
                 o.addClass("ui-state-error");
                 updateTips("Length of " + n + " must be between " +
          min + " and " + max + ".");
                 return false;
             } else {
                 return true;
             }
         }

         function checkRegexp(o, regexp, n) {
             if (!(regexp.test(o.val()))) {
                 o.addClass("ui-state-error");
                 updateTips(n);
                 return false;
             } else {
                 return true;
             }
         }

         $("#dialog-form").dialog({
             autoOpen: false,
             height: 300,
             width: 350,
             modal: true,
             buttons: {
                 "Create an account": function () {
                     var bValid = true;
                     allFields.removeClass("ui-state-error");

                     bValid = bValid && checkLength(name, "username", 3, 16);
                     bValid = bValid && checkLength(email, "email", 6, 80);
                     bValid = bValid && checkLength(password, "password", 5, 16);

                     bValid = bValid && checkRegexp(name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter.");
                     // From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
                     bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com");
                     bValid = bValid && checkRegexp(password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9");

                     if (bValid) {
                         $("#users tbody").append("<tr>" +
                              "<td>" + name.val() + "</td>" +
                              "<td>" + email.val() + "</td>" +
                              "<td>" + password.val() + "</td>" +
                            "</tr>");
                         $(this).dialog("close");
                     }
                 },
                 Cancel: function () {
                     $(this).dialog("close");
                 }
             },
             close: function () {
                 allFields.val("").removeClass("ui-state-error");
             }
         });

         $("#create_user")
      .button()
      .click(function () {
          $("#dialog-form").dialog("open");
      });
     });
</script>
</head>
<body>
    <div id="dialog-form" title="Create new user">
        <p class="validateTips">
            All form fields are required.</p>
        <form id="Form1" runat="server">
        <fieldset>
            <label for="name">
                Name</label>
            <input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" />
            <label for="email">
                Email</label>
            <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
            <label for="password">
                Password</label>
            <input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />
        </fieldset>
        </form>
    </div>
    <button id="create_user">Create new user</button>
    
    
</body>
</html>
--------
please help me to use above code with nested master page
resoure page is :http://jqueryui.com/dialog/#modal-form
Comment posted by aa on Thursday, August 1, 2013 3:54 AM
test here
Comment posted by fredyast on Monday, October 28, 2013 9:54 PM
intente varias cosas y no habia resulto mi inquietud me falta probarlo con un textbox de un control de usuario
Comment posted by it on Wednesday, May 28, 2014 1:05 AM
hjkjgk
Comment posted by test@test.com on Wednesday, July 23, 2014 12:39 AM
test@test.com
Comment posted by dfh on Tuesday, August 12, 2014 1:20 AM
testing file
Comment posted by Hi on Monday, September 22, 2014 4:43 AM
Test
Comment posted by bga on Monday, April 13, 2015 1:07 PM
try this simple code to perform validation on asp.net master page

Working Code: **How to Validate ASP.NET MASTERPAGE Control Using JQuery**

http://allittechnologies.blogspot.in/2015/04/how-to-validate-aspnet-master-page-control-using-jquery.html
Comment posted by tanuj on Sunday, May 17, 2015 9:27 AM
https://www.youtube.com/watch?v=qIGEjHsOzjM