Click here to check my latest exciting videos on youtube
Search Mallstuffs

Flag Counter
Spirituality, Knowledge and Entertainment


Locations of visitors to this page


Latest Articles


Move to top
Trigger custom or manual postback in ASP.NET
Posted By Sarin on Apr 02, 2013     RSS Feeds     Latest Hinduism news
20172 Views

Introduction to postback using JavaScript
One of the most important features of ASP.net is the ability of manually triggering the postback event onto the server. Post back is a process by which the request is posted onto the server based on the event generated by user action. For Ex: when the user selects a dropdown, a post back event is triggered.

How postback works in ASP.NET?
For all the server control except Button and ImageButton, postback is generated by the JavaScript function __doPostBack(). Button and imagebutton uses the client browser functionality to submit the content onto the server. For all other controls, Asp.net runtime automatically insert the definition of __doPostBack() function in the HTML output to initiate a postback onto the page.
As an example, drag a simple linkbutton control and view the aspx page on the browser. IF you view the HTML output of this aspx page, you will see the following code.
    
<form name="form1" method="post" action="Buttons.aspx" id="form2">
<div>
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTQ1OTQ0MTYyOWRkbEhOO740M99GNXoAENzhs8rbwNQ=" />
</div>
<script type="text/javascript">
//<![CDATA[
    var theForm = document.forms['form1'];
    if (!theForm)  {
        theForm = document.form1;
    }
    function __doPostBack(eventTarget, eventArgument)  {
        if (!theForm.onsubmit || (theForm.onsubmit() != false))  {
            theForm.__EVENTTARGET.value = eventTarget;
            theForm.__EVENTARGUMENT.value = eventArgument;
            theForm.submit();
        }
    }
//]]>
</script>    
    </div>
    <a id="LinkButton1" href="javascript:__doPostBack('LinkButton1','')">LinkButton</a>

 As you see above, two hidden elements __EVENTTARGET and __EVENTARGUMENT are created by ASP.net runtime which are then used by __doPostBack function to trigger postback onto the page.
__EVENTTARGET store the ID of the control that raises the postback while
__EVENTARGUMENT can be used to send some additional input/ information to the server.  
On submitting the form, asp.net engine uses these 2 hidden fields to decide what was submitted by the form and then executes the appropriate action.
Third hidden control VIEWSTATE stores in encoded form, the ID of the control plus the method to be called on various user events/actions.  

Raising your own postback event in ASP.NET?
Many times there is a need to raise the postback on some user event. Raising our own custom postback is very simple.
Just write a JavaScript code to call __doPostBack() as shown below

  <script type="text/javascript">
         function Call()  {
             __doPostBack('ControlId', 'ControlInfo');
         }
    </script>

Error encountered while raising custom postback
Above code will not work if your aspx page does not have any control that raises a postback to server. In such cases, you will get the error as shown below
Microsoft JScript runtime error: Object expected
This means you must have at least one control in an aspx page like linkbutton that raises a postback event. Declaring postback control and setting it visibility to false will also not work since the javascript function to perform the necessary action is not included.

Additionally, you may need to add the following code in page load of code behind.
ClientScript.GetPostBackEventReference(this, string.Empty);
This function enables the asp.net engine to initiate custom manual postback event.
  
Now, if you run the code, you may still get an error like
Invalid postback or callback argument
.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page
Asp.net engine has the inbuilt feature of verifying if the postback event is generated from the server control or not. If the postback event is not triggered from server control, it treats it as the hacking attempt or inconsistent behavior and for security purposes, raises the event validation error. IF the postback is valid and successful, asp.net uses the ClientScriptManager.RegisterForEventValidation method to register the postback or callback data for validation.
To bypass this error, you need to explicitly inform the asp.net engine that the event is generating from the trusted source. Adding the below code should do the trick
protected override void Render(System.Web.UI.HtmlTextWriter writer)
     {
        ClientScript.RegisterForEventValidation("lbDoPostBack", "JavaScript");
        base.Render(writer);
    }

Alternatively, change the page property EnableEventValidation to false as shown below
<% @ Page Language="C#" AutoEventWireup="true" CodeFile="PostBack.aspx.cs" EnableEventValidation="false" Inherits="PostBack" %>

Postback in Button and ImageButton control0
There are the only two controls that uses browsers submit behavior to cause postback instead of calling javascript __doPostBack function to post the form. However, you can override this default behavior by setting UseSubmitBehavior property of button control to false (Note this is not possible for ImageButton control). UseSubmitBehavior property tells the asp.net engine to use asp.net postback mechanism or client browser's submit behavior.0

To test it out, take two button controls and set the UseSubmitBehavior of one to true and other to false.
<asp:Button ID="Button1" runat="server" Text="Uses browser submit behavior" UseSubmitBehavior="true" />
<asp:Button ID="Button2" runat="server" Text="Uses asp.net postback mechanism" UseSubmitBehavior="false" />

On running this chunk of code, your HTML output would be
<input type="submit" name="Button1" value="Uses browser submit behavior" id="Button1" />
<input type="button" name="Button2" value="Uses asp.net postback mechanism" onclick="javascript:__doPostBack('Button2','')" id="Button2" />

As you see above, button 2 now uses JavaScript _doPostBack function to submit the form.
  
Demo:
As a simple example, I have taken one button control and one anchor element. On click of these controls, I call JavaScript function to trigger the __doPostBack operation.
<asp:Button runat="server" ID="btnPostBack" OnClientClick="CallServerSideCode(this)" Text="Do Post Back"/><br /><br />
<a id="aTestAnchor" href="javascript:CallServerSideCode('aTestAnchor','Click anchor')">Click anchor</a><br />

     function CallServerSideCode(obj)  {
            alert(obj);
            var id = $(obj).attr("id");
            var val = $(obj).val();
            __doPostBack(id, val);
        }
        function CallServerSideCode(arg1, arg2)  {
            __doPostBack(arg1, arg2);
        }
  
Note that you should pass UniqueID of the control. This is especially important when you have a master page for your aspx page. As a quick solution, set server control ClientIDMode property to Static and then do something like
__doPostBack('<% = Buttonid.UniqueID %> ', 'buttoninfo')

On the code behind side, I have the following code which just retrieves the name of the control that triggered the postback and then displays this name on the text of postback button.
  
ClientScript.GetPostBackEventReference(this, string.Empty);
        string EventTarget = Page.Request.Params.Get("__EVENTTARGET");
        string EventArg = Page.Request.Params.Get("__EVENTARGUMENT");
        if (EventTarget != null && EventTarget != string.Empty)
         {
               btnPostBack.Text = EventTarget + " button make Postback";
        }

Output:
0
As you can see in the debugging above, I am able to retrieve all the parameters (EVENTTARGET and EVENTARGUMENT) that I have passed from my JavaScript _ doPostBack function
  
Conclusion
Thus, we saw how to manually postback the page in an ASP.Net web application. This is very useful in scenarios where we need to trigger the postback on some user event or actions. Hope this article helps you in making a custom postback using javascript.
Note: Images used on this website are either a production of Bhaktivedanta Book Trust(https://www.krishna.com), Iskcon Foundation or were found in google search under "Free to use and share". If any of the images presented here violates copyright issues or infringes anyone copyright or are not under "Fair use", then please bring it to our notice. Read Disclaimer for more.

Share this to your friends. One of your friend is waiting for your share.
Related Articles
Tips and tricks with ajax calendar
Change color of grid view row or cell dynamically
Trigger custom or manual postback in ASP.NET
Ge the total number of HTML elements in a page
Get set field, Properties,events or method using reflection
create new controls in grid view at runtime
Working with forms-Jquery form selector
Demo of Jquery functions and events for dropdownlist
Add, remove or toggle class of HTML control using jquery.
Changing Grid View header and footer at run time

Post Comment