Thursday, May 5, 2011

Call a Javascript function from C#

There are many ways in which you can call a javascript method from your .cs file. The following 2 are best (easiest ;P ) method.

Consider a sample .aspx file as below, where we have a javscript method named - callMe(), our aim in this tutorial is to call this method by using c# code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Resultmaker.ProjectList.WebForm1" %>

<!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></title>
</head>
<body>
<script type="text/javascript">
    function callMe() {
        alert("call successfull");
    }
</script>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

In your .cs file you may use either of the following, to call your javascript method.

// Method 1
Response.Write("<script language='javascript'>alert('Yasser');</script>");
            
//Method 2: The more preferred approach.
string scrname;
scrname = @"<SCRIPT language='javascript'> callMe();" + "</SCRIPT>";
ClientScript.RegisterStartupScript(this.GetType(), "yasser", scrname.ToString(), false);
        


:)

0 comments:

Post a Comment

 

2011 ·Code-Studio by yrus.