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" "">

<html xmlns="">
<head runat="server">
<script type="text/javascript">
    function callMe() {
        alert("call successfull");
    <form id="form1" runat="server">

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);



Post a Comment


2011 ·Code-Studio by yrus.