23 August 2015

Identifying control causing postback in asp.net

If you are developing ASP.NET web application, sometimes you might be wondering how to identity which control was responsible for the page postback. In this post I will try to explain how the ASP.NET page life cycle is going to identity which control caused the postback.

What are EVENTTARGET and EVENTARGUMENT fields in ASP.NET

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />

When ASP.NET web page is rendered, have a look at the page source. In the HTML of the page, you will notice "EVENTTARGET" and "EVENTARGUMENT" hidden fields. Using this fields, ASP.NET is going to identity which control caused the post out of many HTML elements on the page.

How EVENTTARGET and EVENTARGUMENT fields helps to identify HTML element causing the postback?

When page is rendered in the browser, launch the Developer Tools and inspect the HTML element which are doing the postback. When you inspect such HTML elements, you will see something like below.

// Delete HTML button element causing postback
<a href="javascript:__doPostBack('usersGridView','Delete$4')">Delete</a>

// Page navigation HTML element causing postback
<a href="javascript:__doPostBack('usersGridView','Page$4')">View page 4 records</a>
doPostBack() function

If you look at the "__doPostBack" function, it has two arguments.

  1. The first argument specifies the name of the parent control for which the HTML control belongs to. In this case it is a ASP.NET GridView (namespace:System.Web.UI.WebControls)
  2. The second argument specifies, the name of the actual HTML control causing the postback.

And in the ASP.NET code behind file (.aspx.cs file)

You can get to know the control causing the postback by looking at the HTTPRequest's Params

string postBackEventTarget = this.Request.Params["__EVENTTARGET"];
string postBackEventArgument = this.Request.Params["__EVENTARGUMENT"];

By using the combination of "eventTarget" and "eventArgument" you can identify the control causing the postback and take appropriate course of action as per your needs.

1 comment: