Tuesday 21 July 2009

Ways to call JavaScript function from C# in ASP.net

As we all know in ASP.net framework, C# code executes on the server whereas JavaScript code executes in the client's browser. We can't actually "access" JavaScript from the server-side. All that we can do is write the JavaScript function call into the markup and have it execute when all server-side processing is completed and the page renders to the browser.

There are number of workarounds we can achieve this. To demonstrate let us declare a JavaScript Function in the markup page first.



Now we need to decide how we are going to execute this function in our code page.

1. We want to call the function on a page_load event, then we can put the code below to the page_load method:

protected void Page_Load(object sender, EventArgs e)
{
if (!ClientScript.IsStartupScriptRegistered("alert"))
{
Page.ClientScript.RegisterStartupScript
(this.GetType(), "alert", "alertMe();", true);
}
}

2. We want to call the function on a buttion click event, we can write the code as:

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick", "alertMe()");
}

Or

protected void Button1_Click(object sender, EventArgs e)
{
Button1.Attributes["onclick"] = "alertMe()";
}

3. If we have a GridView and we want to call the method when the GridView Row get clicked by the user. This can be very useful in master-detail relationship data. For example, we have a summary GridView report shows customer order headers, when user click on the row, a small window will popup to show the details of the selected order. To do this, we simply add the following line to the GridView RowDataBound event:

GridView1.Attributes["onclick"] = "alertMe()";

No comments:

Post a Comment