Saturday, December 20, 2008

Using the ASP .NET "_doPostBack()" method reference in Javascript



I was assigned to do a task that will need to invoke a javascript method that will perform some client side control state changes and finally submit the page with the "_doPostBack" javascript function. This "_doPostBack" function template is auto generated by the ASP .NET framework and is called when a post back to the server is required as a result of the interaction between the user with the ASP .NET Server Controls(Ex:button click, drop down list selection changes) .

I had first gone for the easy solution and hard coded the function call like this:

<script>
function DoSomeTask()
{
//Do some client side tasks here.
__doPostBack('<control>','');//posts the page back
}
</script>

I then thought should i rely on the hard coded "__doPostBack" method call? What if This function is not generated by ASP .NET under certain conditions? What if the name of the function differs in different browsers? What if Microsoft replaces the function name in the next version of ASP .NET (this application was developed with 1.1) ?

So i searched on the net and found a nice solution. At the server side ,the "GetPostBackClientHyperlink" method of the "Page" object returns the correct script block that does the post back for the ASP .NET server controls. The syntax is:

Page.GetPostBackClientHyperlink(<control>,<argument>);

So i changed the previous javascript block as:

<script>
function DoSomeTask()
{
//Do some client side tasks here.
<%= GetDoPostBackMethodSignature() %>

}
</script>

Where the "GetDoPostBackMethodSignature()" method is declared at the code behind page as:

protected string GetDoPostBackMethodSignature()
{
return Page.GetPostBackClientHyperlink(<Server Control Instance >,string.Empty);

}

Now there is no confustion whether the generated function is named "__doPostBack" or "_sueBillGates".

I trust ASP .NET fully(have no other alternative at the moment though:) ) and sure that my client side codes will not complain about not finding the "_doPostBack" function.

Cheers!

No comments: