Using jQuery with ASP.NET Master Page
Posted by: Suprotim Agarwal
in Category jQuery and ASP.NET
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
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.