July 17, 2009

Access an ASP.NET control on a MasterPage using jQuery




I must have been asked this question numerous times -- How do I access an asp.net control kept in the master page using jQuery? Here’s one of the ways of how to populate the value of an ASP.NET TextBox kept in a MasterPage using jQuery

MasterPage

<%@ Master Language="C#" AutoEventWireup="true"
CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!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>Access Control using jQuery</title>
<
asp:ContentPlaceHolder id="head" runat="server">
</
asp:ContentPlaceHolder>

<
script src="Scripts/jquery-1.3.2.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$("input[id$='txtName']").val("Text Added using jQuery");
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

</
asp:ContentPlaceHolder>
</
div>
</
form>
</
body>
</
html>



ContentPage

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"

AutoEventWireup="true" CodeFile="MasterPage.aspx.cs" Inherits="MasterPage"%>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

</
asp:Content>

<
asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"

Runat="Server">

<
asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</
asp:Content>

Note how we selected the MasterPage using the $("input[id$='txtName']") . This is because the TextBox in the MasterPage gets renamed as shown below:

<input name="ctl00$ContentPlaceHolder1$txtName" type="text" id="ctl00_ContentPlaceHolder1_txtName" />

On running the page, the textbox gets populated using jQuery

image

Check out my other ASP.NET jQuery articles.



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Access an ASP.NET control on a MasterPage using jQuery"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions