Monday, July 27, 2009

Calling JavaScript from ASP.NET Master Page and Content Pages

1. Create a JavaScript function on the fly and call the JavaScript function in the Content Page Page_Load() event
C#
protected void Page_Load(object sender, EventArgs e)
{
const string someScript = "alertMe";
if (!ClientScript.IsStartupScriptRegistered(this.GetType(), someScript))
{
ClientScript.RegisterStartupScript(this.GetType(),
someScript, "alert('I was called from Content page!')", true);
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim someScript As String = "alertMe"
If (Not ClientScript.IsStartupScriptRegistered(Me.GetType(), someScript)) Then
ClientScript.RegisterStartupScript(Me.GetType(), someScript, "alert('I was called from Content page!')", True)
End If
End Sub

2. Call a JavaScript function declared in a .js file from the Content Page
If you have a .js file and want to call the function from your Content Page, then here’s how to do so.
Let’s create a .js file called TestScript.js and add the following function in the .js file.
function insideJS() {
alert('Inside .js');
}
Assuming that your .js file is kept in a Script folder, reference the file in your MasterPage in the following manner.
< head runat="server" >
< title >< /title >
< script src="Scripts/TestScript.js" type="text/javascript" >< /script >
...
Now in your Content Page(in our case Default.aspx.cs or .vb), call the JavaScript function on the Page_Load:
C#

protected void Page_Load(object sender, EventArgs e)
{
if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
{
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "insideJS();", true);
}
}

VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not Master.Page.ClientScript.IsStartupScriptRegistered("alert")) Then
Master.Page.ClientScript.RegisterStartupScript (Me.GetType(), "alert", "insideJS();", True)
End If
End Sub
3. Referencing the .js file from a Content Page instead of the Master page
The approach shown above in Tip 2 works well, however this approach would add a reference to the .js file for every page in the application (since we are adding the .js in the Master Page). If you want to avoid this approach, then remove the reference added to the .js file in Tip 2 in the Master Page. Now add a reference to the .js file from the Content Page using the ‘RegisterClientScriptInclude’ as shown below:
C#
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl(@"Scripts\TestScript.js"));
if (!Master.Page.ClientScript.IsStartupScriptRegistered("alert"))
{
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "insideJS();", true);
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl("Scripts\TestScript.js"))
If (Not Master.Page.ClientScript.IsStartupScriptRegistered("alert")) Then
Master.Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "insideJS();", True)
End If
End Sub
Using this approach, we can avoid referencing the .js file for every content page.
Note: This approach adds the JavaScript reference inside the < body >tag of the page.

4. Declare JavaScript inside the Content page and execute it
If you are looking out to declare JavaScript inside the Content Page, then here’s how to do so. Add the following markup inside the Content page (in our case Default.aspx)
< asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server" >
< asp:Panel ID="panelContent" GroupingText="ContentPage Controls" runat="server" >
< asp:TextBox ID="txtContent" runat="server" >< /asp:TextBox >
< asp:Button ID="btnContent" runat="server" Text="Button" OnClientClick="Populate();" / >
< /asp:Panel >
< script type="text/javascript" language="javascript" >
function Populate() {
{
document.getElementById('< %=txtContent.ClientID% >').value = "Hi";
}
}
< /script >
< /asp:Content >
The markup shown above populates the textbox with some text on a button click.

5. Accessing a Control on the Master Page From a ContentPage using JavaScript
We have added a textbox control to the < body > of the MasterPage as shown below:
< body >
< form id="form1" runat="server" >
< div >
< asp:Panel ID="panelMaster" GroupingText="MasterPage controls" runat="server" >
< asp:TextBox ID="txtMaster" runat="server" >< /asp:TextBox >
< br / >
< /asp:Panel >
< asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server" >

< /asp:ContentPlaceHolder >
< /div >
< /form >
< /body >
We will now access this TextBox ‘txtMaster’ in the ContentPage using JavaScript
To do so, go to the Content page (Default.aspx) and add the following line below the < Page > directive to register the MasterPage
< %@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % >
...
< %@ MasterType VirtualPath="~/MasterPage.master" % >
...
Now in the code behind of Default.aspx.cs or .vb, access the MasterPage control in the following manner
C#
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = (TextBox)Master.FindControl("txtMaster");
string val = tb.ClientID;
string script = @"< script >
function PopulateMaster() {
document.getElementById('" + val + @"').value = 'Via Content Page. Love dotnetcurry';
}
PopulateMaster();
< /script >";
if (!Page.ClientScript.IsStartupScriptRegistered("Mast"))
{
Page.ClientScript.RegisterStartupScript(this.GetType(),
"Mast", script);
}

}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim tb As TextBox = CType(Master.FindControl("txtMaster"), TextBox)
Dim val As String = tb.ClientID
Dim script As String = "< script >" & ControlChars.CrLf & " function PopulateMaster() {" & ControlChars.CrLf & " document.getElementById('" & val & "').value = 'Via Content Page. Love dotnetcurry.com'; " & ControlChars.CrLf & " }" & ControlChars.CrLf & " PopulateMaster();" & ControlChars.CrLf & " < /script >"
If (Not Page.ClientScript.IsStartupScriptRegistered("Mast")) Then
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Mast", script)
End If

End Sub

Observe how we have used the RegisterStartupScript instead of RegisterClientScriptBlock. The main difference is that the 'RegisterStartupScript' method places the JavaScript at the bottom of the ASP.NET page right before the closing < /form > element whereas the 'RegisterClientScriptBlock' method places the JavaScript directly after the opening < form > element in the page. Had we used the 'RegisterClientScriptBlock', the browser would have executed the JavaScript before the text box is on the page. Therefore, the JavaScript would not have been able to find a ‘txtMaster’ and would give a control not found error. Understanding this simple difference between the two methods can save you hours of work!

6. Call JavaScript function from an ASP.NET AJAX enabled Content Page
If your content page is wrapped in an ASP.NET AJAX UpdatePanel, then you cannot use the ClientScript.RegisterStartupScript to call a JavaScript function during a partial-page postback. Instead, use the ScriptManager.RegisterStartupScript() method.
C#
protected void Page_Load(object sender, EventArgs e)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(@"< script language='javascript' >");
sb.Append(@"alert('I love dotnetcurry.com');");
sb.Append(@"< /script >");

ScriptManager.RegisterStartupScript(this, this.GetType(), "ajax", sb.ToString(), false);

}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As New System.Text.StringBuilder()
sb.Append("< script language='javascript' >")
sb.Append("alert('I love dotnetcurry');")
sb.Append("< /script >")

ScriptManager.RegisterStartupScript(Me, Me.GetType(), "ajax", sb.ToString(), False)

End Sub
Observe that the last parameter for RegisterStartupScript() is set to 'false'. This means that the < script > tags will not be added automatically. Since we have already inserted the < script > tags while creating the script in the StringBuilder, we do not need to insert them now.

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates