Accessing master page’s control in content page’s through Javascript might initially seem easy but as you work with it you realize that this may not be very true. While we are writing document.getElementById(‘<%= controlName.ClientID %>‘) it can access only those control which are present in the page. So we cannot give master page control name to find the element. To access master page control name we can write the Javascript in the master page which can be accessed by the content pages. Or in the second work arround if that control is associated with Ajax extender we can use its BehaviourID property to access its content. Following are the ways of accessing master page’s Control in Content page’s Javascript.
What follows is the code for both master page and content page.
|
Master.aspx |
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="TrickMaster.master.cs" Inherits="TrickMaster" %> <%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="cc1" %> <!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> <script type="text/javascript"> function showMaster() { alert(document.getElementById('<%=lblMaster.ClientID %>').innerHTML); } </script> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:Label ID="lblMaster" runat="server" Text="MasterValue"></asp:Label> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <cc1:TextBoxWatermarkExtender ID="TextBox1_TextBoxWatermarkExtender" runat="server" Enabled="true" TargetControlID="TextBox1" BehaviorID="Name" WatermarkText=" "> </cc1:TextBoxWatermarkExtender> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html> ContentPage.aspx: <%@ Page Title="" Language="C#" MasterPageFile="~/TrickMaster.master" AutoEventWireup="true" CodeFile="COntentPage.aspx.cs" Inherits="COntentPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <script type="text/javascript"> // Using behaviour ID function show() { var v = $find("Name").get_Text(); alert(v); $find("Name").set_Text('') } </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:Button ID="Button1" runat="server" Text="Content" ToolTip="call content page javascript function" OnClientClick=" show();" /> <asp:Button ID="Button3" runat="server" Text="Master" OnClientClick="showMaster();" /> </asp:Content>