Using jQuery to Find which ASP.NET Control caused a PostBack

Here’s a simple script that uses jQuery to find out which ASP.NET Button caused a postback. You can similarly implement this script for other ASP.NET Controls too

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Which Control Caused PostBack</title>
<
script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"
type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("input:submit").click(function () {
$("#HiddenField1").val($(this).attr("id")
+ " caused a postback");
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:Button ID="Button1" runat="server" Text="Button1" />
<
asp:Button ID="Button2" runat="server" Text="Button2" />
<
asp:Button ID="Button3" runat="server" Text="Button3" />
<
asp:HiddenField ID="HiddenField1" runat="server" />
</
div>
</
form>
</
body>
</
html>

C#

protected void Page_Load(object sender, EventArgs e)
{
Response.Write(HiddenField1.Value);
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Response.Write(HiddenField1.Value)
End Sub
As you can see, jQuery uses the Hidden field to store the value of the Button ID that caused a postback. The ID is printed using Response.Write()

Now click the Button2 and you get the following message

image



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

2 comments:

slowery said...

I have a concern about doing this - will the client side processing always complete before the server tries to read the hidden field in the postback? I have a case where I am saving a list of items to the hidden field and it dawned on me that there could be a timing issue?

Roboblob said...

Nice post.

Here is how i solved this is ASP.NET:

How to determine which Control caused PostBack on ASP.NET page