Create new account I forgot my password    

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II
Rating: 56 user(s) have rated this article Average rating: 4.2
Posted by: Suprotim Agarwal, on 2/18/2009, in category "ASP.NET 2.0 & 3.5"
Views: this article has been read 110346 times
Abstract: In this article, we will see some common problems and their solutions of calling JavaScript from a Master/Content page. This article is Part II of the series ‘Calling JavaScript from ASP.NET Master Page and Content Pages’ and in this article; we will cover JavaScript in Content Pages.

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II
 
In this article, we will see some common problems and their solutions of calling JavaScript from a Master/Content page. This article is Part II of the series ‘Calling JavaScript from ASP.NET Master Page and Content Pages’ and in this article; we will cover JavaScript in Content Pages. Part I of this article can be read over here Calling JavaScript from ASP.NET Master Page and Content Pages - Part I
Call JavaScript from Content Page
Here are some common scenarios of executing JavaScript from a Content Page.
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
In our previous article, we saw how in Tip 5 To access a control on the ContentPage From a Master Page using JavaScript. In this tip, we will see how to access a control kept on the MasterPage from a ContentPage. Do the following:
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.
These were some common scenarios and their solutions when using JavaScript on Content Pages. You can read some common scenarios of using JavaScript on Master Pages as well. I hope you liked the article and I thank you for viewing it.
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email 









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Digambar on Thursday, March 05, 2009 9:32 AM
Thanks for the article. Just what I was looking for.
Comment posted by Jaime Premy on Saturday, March 21, 2009 12:12 AM
Hi,you sure did a good job and covered lots of scenarios. But there's one missing for which i've been looking around for, for some weeks now: Javascript called from within a user control. It's a Master/content situation with a rollover menu created in the ascx, which in turn is placed on the lefthand side of the master, the rollover images, the js script and the css stylesheet are all in 1 folder, that I placed in the root directory of the site. All goes well until I load a content page in a subdirectory. In this case the hyperlinks in the js get an extra folderlevel appended to the url and I get a 404 error. For the time being I solved this by placing a copy of the script folder in every subdirectory, but u can imagine the maintenance nightmare this represents. The guys on asp.net forum tried exhaustively to help me out, but to no avail (http://forums.asp.net/p/1397748/3021853.aspx#3021853). But I'm sure this should be doable somehow. U might wanna take a look into it one of these days, just to stimulate your neurons a bit more.
Regards,
Premy
Comment posted by Tom D on Wednesday, April 22, 2009 11:16 AM
Thanks!  Was looking for a way to parse a textbox in an UpdatePanel using Javascript and you helped me out with the ClientID that I was missing.
Comment posted by Abhilash on Thursday, April 30, 2009 2:26 AM
Tip#5 and Tip#6 was just great.
Tip#3 stll confuses me.
Part II, is really worth bookmarking.
Thanks for the nice post.
tc
Comment posted by Vinny on Thursday, April 30, 2009 10:13 PM
Very good article indeed.  It did save me lot of time figuring out the differences between the RegisterClientScriptBlock and RegisterStartupScript.  Thanks for covering in detail all the different scenarios.  I look forward to more of these articles.
Comment posted by Thanigainathan on Friday, May 08, 2009 3:47 PM
Hi,

very nice article. Lot of practical oriented scenarios covered.Will be a good reference.

Thanks,
Thani
Comment posted by Nanda on Friday, May 08, 2009 4:01 PM
Good Work done...Keep it up!!
Comment posted by Suprotim Agarwal on Saturday, May 09, 2009 3:31 AM
Abhilash, Vinny, Thanigainathan, Nanda: Thanks for your comments!
Comment posted by Brahm Gupta on Monday, May 11, 2009 2:39 AM
Thanks thanks... For me this article was written by god.. I was trying to call my JS Code within AJAX Enabled Content page.. Nd i was stuck in it and stumbled across this article... Thanks again..
Comment posted by Suprotim Agarwal on Monday, May 11, 2009 8:48 PM
Brahm: LOL. Glad you liked it!
Comment posted by jesus on Monday, July 13, 2009 11:35 AM
This is crap.
Comment posted by Venkatesan Prabu on Thursday, August 06, 2009 2:05 AM
Team,

  Am having a javascript function in .js file. I need to access the function in my content page. I have tried some of the code. But, its not working.

  please tell me the way to include css file in the content page.

Thanks and REgards,
Venkatesan Prabu .J
http://venkattechnicalblog.blogspot.com/
Comment posted by Adrian on Friday, August 07, 2009 5:50 AM
You my friend are a legend!
Combined this with the x.js script on an update panel and it works like a dream! saved me much sleep and troubles. thanks a million times over!!
Ade
Comment posted by Suprotim Agarwal on Tuesday, August 11, 2009 1:23 AM
Venkatesan: Post some sample code

Adrian: Glad you liked the stuff!
Comment posted by K.Bala on Thursday, September 17, 2009 2:14 AM
Thanks dotnetcurry
below help has worked for me.
        Page.ClientScript.RegisterClientScriptInclude("selective", ResolveUrl("Scripts\TestScript.js"))


Comment posted by P Dao on Saturday, September 19, 2009 2:43 PM
Using the asp club starter kit and I'm trying to move the javascript from default.aspx to its own js file on the root (ShowDuration.js). I've tried using example #3 with no success replacing TestScript with ShowDuration in the code and placing it in the <body>.

Help would be greatly appreciated! Thanks
Comment posted by P Dao on Saturday, September 19, 2009 2:59 PM
Using the asp club starter kit and I'm trying to move the javascript from default.aspx to its own js file on the root (ShowDuration.js). I've tried using example #3 with no success replacing TestScript with ShowDuration in the code and placing it in the <body>.

Help would be greatly appreciated! Thanks
Comment posted by Rashadovich on Thursday, October 01, 2009 5:17 AM
very very very Thanks for this amazing article

thx very much
Comment posted by chris on Wednesday, October 21, 2009 12:56 PM
Thanks!  Greatly appreciated.  But, how (exactly) would I call a javascript function (say a simple alert();) from a method (NOT page_load) inside my content page's codebehind?  Theses examples are not practical in terms of real world application, as the only reason you would want to call a popup is to warn a user or to display some values, etc.  Thanks.
Comment posted by Abhay Mhatre on Tuesday, December 01, 2009 4:02 AM
Is it possible to call javascript function from code behind that return some value? e.g

<script type="text/javascript">
showaddress(){
// some block of code
return number;
}
</script>


<asp:button id="btnsbt" runat="server" onClick="btn_Click" />

protected btn_Click(object, e){
   // call java script function

// i want to fetch return value of the javascript function to produce next result or produce new results is it possible?  else what can be other alternative ?
}
Comment posted by Dave Hetesi (www.hetesi.com) on Wednesday, January 06, 2010 9:49 AM
See the following article for adding intellisense for javascript files to VS2008.

http://blogs.ipona.com/james/archive/2009/01/14/jquery-1.3-and-visual-studio-2008-intellisense.aspx

Reference files via the ScriptManager in a master page to have them available on all pages.  The following makes jQuery available on all pages and with the added vsdoc file provides intellisense.

<asp:ScriptManager ID="s" runat="server">
     <Scripts>
          <asp:ScriptReference Path="~/javascript/jquery-1.3.2.js" />
     </Scripts>
</asp:ScriptManager>
Comment posted by Anand.T on Thursday, January 07, 2010 4:06 AM
How to use page protection Java script in html page (or) how to avoit in right click my web page.i need html page source.
Comment posted by Suprotim Agarwal on Thursday, January 07, 2010 4:42 AM
Anand: There is no sure shot way of protecting your JavaScript.
Comment posted by Svetovid on Friday, January 29, 2010 8:54 AM
Nice article!
But applying your code from part II paragraph 3 I have found some difficulties.
Whereas my content page contains AjaxToolkit Extenders they're all disabled and their html code is display in the very bottom of the page.
How could I pass over this obstacle.
Comment posted by M. Selvaraaj Prabu on Friday, April 16, 2010 5:02 AM
Hi, Very nice. you have covered several scenarios. But I found another problem in my code. If the control (button) is placed in side "updatepanel" it does not work at all. If I remove teh updatepanel stuff it works. Since I dont need the panel now, I removed and continuing. Not sure, whehter you need to look in this issue and give a solution.

Thanks very much for your time to help geeks like us.
Comment posted by Snigdharani Behera on Friday, July 09, 2010 3:11 AM
This is a very nice post. But I would like to know a little more about the 5th point... "5. Accessing a Control on the Master Page From a ContentPage using JavaScript" How do i change the value of the master page's control in javascript directly in aspx page. I do not want to call the javascript function from code behind. Basically i need to swap the value of a label placed in master page based on some click in client side. How can I do this?
Comment posted by P.Thirunavukkarasu on Saturday, August 07, 2010 8:38 AM
help me
Master page in Dot.net
=======================
how to use two body tag in content page

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER