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






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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