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, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Using jQuery to Find which ASP.NET Control caused a PostBack"
  1. slowery said...
    June 8, 2010 at 10:15 AM

    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?

  2. Roboblob said...
    June 9, 2010 at 6:19 AM

    Nice post.

    Here is how i solved this is ASP.NET:

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

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions