Search This Blog

Thursday, 6 June 2013

Calling postback event from JavaScript


I had a situation to force page post back via JavaScript; this has been for a SharePoint Web Part as there is an issue sometimes with a second post back being disabled. Also found it helpful for when doing a SharePoint dialog callback.

Then I referred this link http://gowrishaan.wordpress.com/2009/05/20/calling-postback-event-from-javascript/, here they gave an idea to fire the postback event from JavaScript. The key is

__doPostBack(“ ”,””);

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

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.

You can download sample .Net Application from here
You can download sample SharePoint Webpart from here

Reference

No comments:

Post a Comment