Powered by Blogger.

Monday, February 24, 2014

Call JavaScript function from code behind file in Asp.Net



In this post we will discuss how to call a JavaScript function from a code behind file in Asp.Net. Also you can check out my previous posts on:

- Increase column size in sql server 2008

- The underlying provider failed on Open error in Asp.Net Entity framework

- Sealed class and Sealed method in C#.Net

In this example, we will call a JavaScript method from a button click.

.Aspx Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default18.aspx.cs" Inherits="Default18" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call JavaScript method from code behind file</title>
     <script type="text/javascript">
         function JavaScritFromCodeBehind() {
             alert('Welcome to JavaScript Call from Code Behind file');
         }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnClick" runat="server" Text="Click to call JavaScript Function" OnClick="btnClick_Click" />
    </div>
    </form>
</body>
</html>

.cs Code:
protected void btnClick_Click(object sender, EventArgs e)
    {
        Page.ClientScript.RegisterStartupScript(this.GetType(),
            "Welcome", "JavaScritFromCodeBehind();", true);
    }
or if you are using AJAX, then you can try like this:
 ScriptManager.RegisterStartupScript(this, this.GetType(), "CallMyFunction", "JavaScriptFunctioName();", true);

Now when you run the code and click on the button.





0 comments

Post a Comment