CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net

By Satheesh Babu
Posted On Mar 04,2010
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 10
Category: ASP.Net
Print this article.

Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net

 

Postback is a mechanism where the page contents are posted to the server due to an occurrence of an event in a page control. For example, a server button click or a Selected Index changed event when AutoPostBack value is set to true. Before moving into the subject, we will discuss some of the basics of the ASP.Net postback framework which will help us to use this feature efficiently.

 

How the PostBack Occurs?

All the webcontrols except Button and ImageButton control will call a javascript function called __doPostBack() to post the form to server. Button and ImageButton control will use the browsers ability and submit the form to the server. ASP.Net runtime will automatically insert the definition of __doPostBack() function in the HTML output when there is a control that can initiate a postback in the page.

To know this, drag a LinkButton control into the page and execute the page. You can see the __doPostBack() function will get automatically added to the page output. Refer below,

<body>

    <form name="form1" method="post" action="Buttons.aspx" id="form1">

<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>

   

    </form>

</body>

</html>

 

In the above code, you can see the definition of __doPostBack() method(bolded) automatically inserted.

 

What does __doPostBack() method do?

It is very clear from the above method definition that the method accepts 2 arguments, eventTarget and eventArgument. These arguments values are in turn populated to hidden fields, __EVENTTARGET and __EVENTARGUMENT.

__EVENTTARGET

This field is populated with the ID of the control that raises the postback in order to identify it by the server.

__EVENTARGUMENT

This field can be used by the control to send some additional information to the server. Later sections of this article will discuss more on this field and its usages.

 

These 2 hidden fields are again inserted by the ASP.Net runtime when it inserts __doPostBack method.

 

Moving to our subject now, if we want to raise a postback manually without an event then it is as simple as calling the __doPostback() method using javascript.

 

How to Raise a Postback from JavaScript?

To do this, we need to just call the __doPostBack() function from our javascript code.

Refer below,

<script type="text/javascript">

        function CallServer() {

               __doPostBack('','');

        }

    </script>

 

When the above function is called, it will raise a postback to server.

Note

Sometimes, when the above code is executed we may get the below error,

Microsoft JScript runtime error: Object expected

 

As i said earlier, ASP.Net runtime will insert the definition of __doPostBack() automatically only when there is a control that can initiate a postback in the page. In this case, your page might not have a control that can raise the postback. ASP.Net is brilliant enough so that it outputs the __doPostBack() function only if there is a control that can raise postback.

We will move to the next section and understand how we can take care of these scenarios.

 

Emitting __doPostBack()  postback method manually

The ClientScriptManager class released in .NetFramework has method called GetPostBackEventReference() which can emit the definition of __doPostBack method into our page. Include the below code in your page load,

protected void Page_Load(object sender, EventArgs e)

    {

        ClientScript.GetPostBackEventReference(this, "");

    }

 

The above code will insert the __doPostBack() method into your webpage.

 

Raising a Control Event

Sometimes, you may have a scenario where you may need to raise a control’s event from a javascript based on some business logic. For example, if you want to raise a DropDownList Selected Index changed event or a LinkButton click event manually, then you can call __doPostBack() method by passing its ID. Refer the below code.

<script type="text/javascript">

        function CallServer() {

               __doPostBack('lbDoPostBack','');

        }

    </script>

 

You should pass the UniqueID of the control when you have associated master page in the __doPostBack() method above.

When you call __doPostBack() method without any argument (as in section Raising Postback from Javascript) then it will call only the Page_Load event.

 




More on __EVENTARGUMENT

As i said earlier, the controls can use this argument to send some additional information to the server.  Read the msdn article here where they have used this argument to know the id of the element that raised the postback when there is a custom control that has more than one postback element.

OR

We can use this argument to identify whether the postback is triggered by the control or by the javascript. In the above example(Refer previous section), i have said that we can raise an event of a page control from javascript based on some business logic. Suppose, if we want to differentiate the postback raised by the control and javascript, we can use the __EventArgument parameter.

 

<script type="text/javascript">

        function CallServer() {

            __doPostBack('lbDoPostBack', 'JavaScript');

          

        }

    </script>

CodeBehind

 protected void lbDoPostBack_Click(object sender, EventArgs e)

    {

        if(Request["__EVENTARGUMENT"] == "JavaScript")

        {

            Response.Write("Called by Javascript!!");

        }

        else

        {

            Response.Write("Called by LinkButton!!");

        }

    }

 

The above code will actually throw a security exception like below,

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

 

To overcome this error, use the ClientScript.RegisterForEventValidation() method of ClientScriptManager class to say the server that the event originating is trusted.

Refer below,

protected override void Render(System.Web.UI.HtmlTextWriter writer)

    {

        ClientScript.RegisterForEventValidation("lbDoPostBack", "JavaScript");

        base.Render(writer);

    }

Include the above code in your codebehind.

 

Conclusion

Thus, we have understood how a postback in ASP.Net web application works. There are times where we need to raise a postback ourselves apart from using ASP.Net controls. Thus, understanding this article will help us to make a custom postback using javascript when required.

 

 

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Really helpful
Hi thanks for this - it was really helpful
Save my life
As I am beginners to the vb.net, I am struggling for this solution since last 3 days.Finally it works...

Fabulous work..

Thank you very much...
Solved
Very helpful information. I wasn't able to submit the form after using e.preventDefault(). This article solved my problem.

Thanks a Lot.
Awesome article
Awesome article.
Thank you very much.
Keep it up.
Awesome article
Thank you very much for your article.
Very Helpful!!!
Your article is full of marvelous information. thanks for help us
Re:Doing or Raising Postback using javascript
Very nice article........ it has solved my problem, i was facing regarding post back using javascript......

thx............. very helpful
Feedback
Very useful atricle. Everything clearly explained.
Thank you very much !!!!
Akamai can cause issues with __doPostBack when used incorrectly
I had a similar issue when working with Akamai. It turned out that Akamai was modifying the user-agent string because an setting was being applied that was not needed.

This meant that some .NET controls did not render __doPostBack code properly. This issue has been blogged here:

http://www.dotnetlite.com/2010/06/21/loss-of-__dopostback-code-after-protecting-a-site-with-akamai/
Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net
This article was very helpful.. Thanks a lot .