26 August 2013

Javascript Calling from Code behind in ASP.NET

Calling a javascript function in an aspx page is a general scenario but calling the same function from code behind and registering a javascript in the code behind and dynamically calling that function is something new and have to learn. So in this article you can find out different scenarios of calling a javascript function.

1.       Calling a javascript function from aspx page (general way)
2.       Calling a javascript function from code behind
3.       Registering a javascript function dynamically and calling it through an event.
4.       Dynamically calling a dynamically registered javascript function.

ASPX PAGE:
In the aspx page we can simply writes the code like as following and in an any events of control we can fire the function.

Default.aspx:  
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function CallingFun()
    {
        alert('Hi, Iam javascript function. Calling from asp.net');
    }
    function test()
    {
        alert('Hi, This is from button(general way)’);
    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<%--calling test function here--%>
    <input type="button" value=”Click Me” onclick=”test()” />

<%--calling testing function which is dynamically registered from code behind--%>
    <input type="button" runat="server" id="btnclick" value="Call Code behind Javascript method" onclick="testing()"/>
    </div>
    </form>
</body>
</html>


Code Behind:
using System;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        javaScript();
        System.Web.UI.ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "Script""CallingFun();"true); 
    }
    private void javaScript()
    {
        string script = @"<script type=""text/javascript"" language=""Javascript"">
            function testing()
            {
                            alert('Hey Dude, Im from code behind');                                                                                                                 
            }
            </script>";
        Page.ClientScript.RegisterClientScriptBlock(GetType(), "sivagtest", script);
    }
}