Calling JavaScript from ASP.NET Master Page and Content Pages - Part I

Posted by: Suprotim Agarwal , on 2/16/2009, in Category ASP.NET
Views: 238217
Abstract: Calling JavaScript from Master and Content Pages confuses a lot of developers. In this article, we will see some common problems and their solutions of calling JavaScript from a Master/Content page.
Calling JavaScript from ASP.NET Master Page and Content Pages - Part I
 
Calling JavaScript from Master and Content Pages confuses a lot of developers. In this article, we will see some common problems and their solutions of calling JavaScript from a Master/Content page. This article is Part I of the two part series and will cover JavaScript in Master Pages. The next article will cover JavaScript in Content pages.
Update: Part II of this article can be read over here Calling JavaScript from ASP.NET Master Page and Content Pages - Part II
Call JavaScript From Master Page
You can call an existing JavaScript function from a Master Page or can create one on the fly. Here are some common scenarios:
1. Create a JavaScript function on the fly and call the JavaScript function in the MasterPage Page_Load() event
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        string someScript = "";
        someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(), "onload", someScript);
    }
VB.NET
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim someScript As String = ""
        someScript = "<script language='javascript'>alert('Called from CodeBehind');</script>"
        Page.ClientScript.RegisterStartupScript(Me.GetType(), "onload", someScript)
    End Sub
 
The Page.ClientScript.RegisterStartupScript() allows you to emit client-side script blocks from code behind. More info can be found over here http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerstartupscript.aspx
2. Call an existing JavaScript function on MasterPage Page_Load() event
Let us assume you have an existing JavaScript function declared in between the <head> tags, then here’s how to call that function from Page_Load()
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function invokeMeMaster() {
            alert('I was invoked from Master');
        }
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
C#
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.ClientScript.IsStartupScriptRegistered("alert"))
        {
            Page.ClientScript.RegisterStartupScript
                (this.GetType(), "alert", "invokeMeMaster();", true);
        }
 
    }
VB.NET
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If (Not Page.ClientScript.IsStartupScriptRegistered("alert")) Then
            Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "invokeMeMaster();", True)
        End If
    End Sub
3. Call JavaScript function from MasterPage on Button click
If you want to call a JavaScript function on a Button click, then here’s how to do so:
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function invokeMeMaster() {
            alert('I was invoked from Masterdotnetcurry');
        }
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
In the <body> tag, add a Button and use the OnClientClick to call this function
<asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return invokeMeMaster();"/>
 
The OnClientClick() is called before the postback occurs. This gives us a place to check for some condition and cancel the submit if the condition is not satisfied. We will see an example in Tip 6.
4. Access a control on the MasterPage using JavaScript
If you have a control on the MasterPage and need to access it using JavaScript, then here’s how to do so. In this sample, we will test the length of the TextBox to see if there are 5 or more letters. If the number of letters is less than 5, the form submit will be cancelled.
Add a TextBox and a Button control in the MasterPage (outside the ContentPlaceHolder) 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>
            <asp:Button ID="btnMaster" runat="server" Text="Button" OnClientClick="return accessMasterControl();" />
            <br />
        </asp:Panel>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
       
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
In the <head> element of the MasterPage, add the following code:
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function accessMasterControl() {
            if (document.getElementById('<%=txtMaster.ClientID%>').value.length <= 5) {
                alert('Minimum 5 characters required')
                return false;
            }
            else { return true;}
        }
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
5. Access a control on the Content Page from a MasterPage using JavaScript
If you have a control on the Content Page which has to be accessed in the MasterPage using JavaScript, then here’s how to do so:
On the Content Page, create a TextBox as shown below :
<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:Panel>
</asp:Content>
 
Now access and populate the TextBox ‘txtContent’ from the MasterPage
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function accessControlContentPage() {
var txtCont = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("txtContent").ClientID %>');
    txtCont.value = "I got populated using Master Page";               
}
    </script>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
6. Ask user before submitting the form on a MasterPage
In order to ask the user for a confirmation before submitting the form, you can either use code behind or can use simple mark up as shown below:
Declare a Button control that causes postback and write the following code in MasterPage.master.cs or .vb
C#
protected void Page_Load(object sender, EventArgs e)
{
    string myScript = @"<script type='text/javascript'>
    function askBeforeSubmit() {
    var msg = 'Are you sure?';
    return confirm(msg);
    }
    </script>";
    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MakeSure", myScript);
    form1.Attributes.Add("onsubmit", "return askBeforeSubmit();");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
      Dim myScript As String = "<script type='text/javascript'>" & ControlChars.CrLf & "    function askBeforeSubmit() {" & ControlChars.CrLf & "    var msg = 'Are you sure?';" & ControlChars.CrLf & "    return confirm(msg);" & ControlChars.CrLf & "    }" & ControlChars.CrLf & "    </script>"
      Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MakeSure", myScript)
      form1.Attributes.Add("onsubmit", "return askBeforeSubmit();")
End Sub
If you want to avoid a code-behind approach, you can ask the user for a confirmation by using the OnClientClick() on the Submit button
<asp:Button ID="btnMaster" runat="server" Text="Button"
OnClientClick="return confirm('Are you sure?');"/>
These were some common scenarios and their solutions when using JavaScript on MasterPages. In the next article, we will see how to use JavaScript in Content Pages. Update: Part II of this article can be read over here Calling JavaScript from ASP.NET Master Page and Content Pages - Part II
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 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by Kamal on Tuesday, February 17, 2009 2:41 AM
Hi,

Good article about javascript.Very Useful.
Comment posted by Kamal on Tuesday, February 17, 2009 2:45 AM
Hi,

Good article about javascript.Very Useful.
Comment posted by Chuck Sndyer on Tuesday, February 17, 2009 10:19 AM
Great article, but only 3 days late.  Just had to work this out by myself (with the help of the internte) for my project.  Accessing a nested master page from the content page.  Took a few minutes, and this article would have reallly helped.  Ended up using the Page.ClientScript.RegisterClientScriptBlock which is quite easy to use.
Comment posted by Suprotim Agarwal on Wednesday, February 18, 2009 8:37 PM
Chuck :) hopefully both the articles will be useful on your next project! Make sure you check the second part of this article.
Comment posted by Boyan Kostadinov on Wednesday, April 22, 2009 4:36 AM
Horrible way to mix server side and client side code. Why not use jQuery or Prototype and use class names to find the controls and apply envets?
Comment posted by Abhilash on Thursday, April 30, 2009 2:09 AM
I really like the tip#5.
Thats a new one to me.
Thanks.
Comment posted by GH on Thursday, April 30, 2009 5:39 AM
You really shouldn't be advocating use of creating client-side functions using such methods; it's far more efficient to put the JS in a .js file so it's cached on the client and then call it from a registerstartupscript or similar means.

jQuery or Prototype won't always give you exactly what you need, especially if you need to pass dynamic values into client-side functions, but there are far cleaner ways to do it.
Ultimately this is a beginners article but the concepts shouldn't be applied to any decent website!
Comment posted by Oleg Kashapov on Thursday, April 30, 2009 3:12 PM
Another "master piece" from programming "guru". I totally agree with GH and Boyan Kostadinov above.
Comment posted by Suprotim Agarwal on Friday, May 1, 2009 1:29 AM
GH: I have mentioned these points in the second part of this article. Check out Tip 2 and 3 over here:

http://www.dotnetcurry.com/ShowArticle.aspx?ID=274
Comment posted by James on Monday, May 4, 2009 10:34 AM
very very good and very useful
Comment posted by Test on Wednesday, November 11, 2009 3:52 AM
Test
Comment posted by Olivier on Wednesday, December 2, 2009 7:44 PM
great article, I posted on the asp.net forum.   I  hope you don't mind
Comment posted by Jennifer on Friday, January 29, 2010 11:51 AM
Very good article. But when I try the #5 (that is what I am looking for), I keep get an error "Object reference not set to an instance of an object.". It will be really appritiate if some one can tell me what is the problem.

Thanks.
Comment posted by param on Monday, August 2, 2010 11:26 AM
how to get the images into database to from and display dynamically

Comment posted by novice on Monday, January 17, 2011 12:41 AM
I have a master page MasterMain and content page MyTest.
I have a text box control txtValue in my content page.
In the MyTest.aspx.cs page, Page Load of the content page, I want to assign some value to the Text property of the textbox.
In the MyTest.aspx, I want to extract that value by doing document.getElementID().value

My problem right now is, i am able to extract the value if I hard code it in the textbox property from the property explorer.
If i try to assign the value in code in page load event like txtValue.Text = "abc",
it returns blank or null. It is  not able to find that control or able to assign any value through that line of code.

Can anybody help please?

Thanks!
Comment posted by suganya on Tuesday, February 1, 2011 4:11 AM
good example....keep it up...the way u presented is good.thank u...
Comment posted by Neeraj on Friday, March 11, 2011 2:41 AM
Assign the variable inside below code.
If Page.IsPostBack = False Then
end if
Comment posted by mano on Wednesday, March 23, 2011 4:59 AM
Thanks for this article! very useful for me
Comment posted by Dryan57 on Monday, May 9, 2011 9:47 AM
Grande!!
Me sirvio el inciso 1! :D muy buen aporte
Comment posted by raj tripathi on Saturday, April 21, 2012 5:25 AM
how to use java script please give me some importent tips


raj tripathi
Comment posted by Buosi on Saturday, May 5, 2012 11:21 AM
Nice article! Thanks
Comment posted by Sreeni on Wednesday, May 30, 2012 3:40 AM
how to implement java script please give me some importent tips
and correct tips
Comment posted by Fabian Ortiz on Thursday, January 10, 2013 8:28 PM
thank you for this material, I need your help, I make a web page where I use this material but when return a value of javascript function is visible but if I press other button for to send to database this value is erased and I dont have idea how solute this please help me.
Comment posted by krishnaraj on Tuesday, April 16, 2013 8:00 AM
awesome man
Comment posted by Sam on Friday, August 23, 2013 5:57 AM
useful articles.

I found one helpful articles here to http://blogfornet.com/2013/08/call-javascript-function-on-asp-net-content-page-body-load/

which describe sort and sweet.
Comment posted by LĂșcio on Tuesday, January 7, 2014 6:59 AM
Thank you very much for this article.  I was having a problem using arrow Keys and a máster page but with tip number 5 I solved the problem.  Have a great 2014!
Comment posted by Suprotim Agarwal on Tuesday, January 7, 2014 7:04 PM
@Lúcio Happy 2014 to you too!
Comment posted by Naman Vaishnav on Saturday, February 8, 2014 10:39 PM
sir,  In ContentPlaceHolder i create .aspx page with different js/css file..
bt this css/js  is affect on my master page design ? how can i apply js/css file specific div region.. not whole html code? please mail me..  
Comment posted by nit on Tuesday, February 18, 2014 6:06 AM
perfect code and it is very helpfull.

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