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 -
<%@ Page Language="vb" AutoEventWireup="true" <span style="color: rgb(255, 0, 0);">MasterPageFile="~/MasterPage.Master"</span>
title="JUST A TEST" %>
<span style="color: rgb(255, 0, 0);"><%@ MasterType VirtualPath="~/MasterPage.Master" %></span>

<script runat="server">
Sub Page_Load(ByVal Sender As Object, ByVal e As System.EventArgs)

Dim mtb As Label
Dim tb As TextBox
tb = FormView1.FindControl("EMAILTextBox")
mtb = Master.FindControl("Label1")
mtb.Text = tb.Text

End Sub 
<asp:content id="Content1" contentplaceholderid="head" runat="server">
<asp:formview id="FormView1" runat="server" datasourceid="SqlDataSource1" defaultmode="Edit">
<asp:textbox id="LASTNAMETextBox" runat="server" text="'<%#">' />

<asp:textbox id="FIRSTNAMETextBox" runat="server" text="'<%#">' />

<asp:textbox id="OPHONETextBox" runat="server" text="'<%#">' />

<asp:textbox id="EMAILTextBox" runat="server" text="'<%#">' />

<asp:linkbutton id="UpdateButton" runat="server" causesvalidation="True" commandname="Update" text="Update">
<asp:linkbutton id="UpdateCancelButton" runat="server" causesvalidation="False" commandname="Cancel" text="Cancel">
..................... codes ........................

master page (MasterPage.Master) -
<%@ Master Language="VB" AutoEventWireup="false"  Inherits="JustATest.MasterPage" %>

<script language="javascript" type="text/javascript">

function pfb(){
var data1;
document.write(<span style="color: rgb(255, 0, 0);">document.getElementById("<%= Label1.ClientID %>").innerText</span>);

<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">