How to call JavaScript function in asp.net code behind c#

{0 Comments}

For some reasons I have to call JavaScript on the page from the code behind in c#. For this I stumbled across many website and forums I got the whole things in different pieces so, I this article I put them one way to have complete overview. Let’s see how we can call JavaScript function from the code behind of the c #page in asp.net.

                In the design page a JavaScript function is added with some name and a simple line in code behind to call that function. You can download this sample page by clicking on these link call_javascript_from_codebehind.

 HTML |  copy code |? 
01
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="call_jsf_codebehind.aspx.cs"
02
    Inherits="_Default" %>
03
 
04
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
05
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
06
 
07
<html xmlns="http://www.w3.org/1999/xhtml">
08
    <head runat="server">
09
        <title>Untitled Page</title>
10
 
11
        <script type="text/javascript">
12
        function myFunction()
13
               {
14
                alert("Hello World!");
15
               }
16
        </script>
17
 
18
    </head>
19
    <body>
20
        <form id="form1" runat="server">
21
        <div>
22
        </div>
23
        </form>
24
    </body>
25
</html>

Now in code behind the main line is in page load event

 C# |  copy code |? 
01
using System;
02
using System.Configuration;
03
using System.Data;
04
using System.Linq;
05
using System.Web;
06
using System.Web.Security;
07
using System.Web.UI;
08
using System.Web.UI.HtmlControls;
09
using System.Web.UI.WebControls;
10
using System.Web.UI.WebControls.WebParts;
11
using System.Xml.Linq;
12
 
13
public partial class _Default : System.Web.UI.Page 
14
{
15
    protected void Page_Load(object sender, EventArgs e)
16
    {
17
        System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "script", "myFunction()", true);
18
    }
19
   }
20

.

 

Leave a Comment

Your email address will not be published.