Thursday, April 30, 2009

How To Pass ASPX Page Control Parameter to Master Page Javascript Function

Microsoft introduced the Master Page concept at .NET 2.0 which supports developing a common look and feel across the entire web site. However, there is no directly way to pass the value from the web pages controls to master page' javascript section. I have tested a simple example for me to do it easily -

The codes below passing the value of FormView control (FormView1) field named "EMAILTextBox" to Label1 at Master page, then the Javascript function pfb() retrieve the value from the Label field - "Label1"


the aspx page -
  1. <%@ Page Language="vb" AutoEventWireup="true" <span style="color: rgb(255, 0, 0);">MasterPageFile="~/MasterPage.Master"</span>  
  2. title="JUST A TEST" %>  
  3. <span style="color: rgb(255, 0, 0);"><%@ MasterType VirtualPath="~/MasterPage.Master" %></span>  
  4.   
  5. <script runat="server">  
  6. Sub Page_Load(ByVal Sender As ObjectByVal e As System.EventArgs)  
  7.   
  8. Dim mtb As Label  
  9. Dim tb As TextBox  
  10. tb = FormView1.FindControl("EMAILTextBox")  
  11. mtb = Master.FindControl("Label1")  
  12. mtb.Text = tb.Text  
  13.   
  14. End Sub   
  15. </script>  
  16. <asp:content id="Content1" contentplaceholderid="head" runat="server">  
  17. <asp:formview id="FormView1" runat="server" datasourceid="SqlDataSource1" defaultmode="Edit">  
  18. <edititemtemplate>  
  19. LASTNAME:  
  20. <asp:textbox id="LASTNAMETextBox" runat="server" text="'<%#">' />  
  21.   
  22.   
  23. FIRSTNAME:  
  24. <asp:textbox id="FIRSTNAMETextBox" runat="server" text="'<%#">' />  
  25.   
  26.   
  27. OPHONE:  
  28. <asp:textbox id="OPHONETextBox" runat="server" text="'<%#">' />  
  29.   
  30.   
  31. EMAIL:  
  32. <asp:textbox id="EMAILTextBox" runat="server" text="'<%#">' />  
  33.   
  34.   
  35. <asp:linkbutton id="UpdateButton" runat="server" causesvalidation="True" commandname="Update" text="Update">  
  36. <asp:linkbutton id="UpdateCancelButton" runat="server" causesvalidation="False" commandname="Cancel" text="Cancel">  
  37. </edititemtemplate>  
  38. ..................... codes ........................  
  39. </asp:Content>  

master page (MasterPage.Master) -
  1. <%@ Master Language="VB" AutoEventWireup="false"  Inherits="JustATest.MasterPage" %>  
  2.   
  3. <script language="javascript" type="text/javascript">  
  4.   
  5. function pfb(){  
  6. var data1;  
  7. document.write(<span style="color: rgb(255, 0, 0);">document.getElementById("<%= Label1.ClientID %>").innerText</span>);  
  8. }  
  9. </script>  
  10.   
  11.   
  12. .............  
  13. <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">  
  14.   
  15. </asp:contentplaceholder>