Postback from javascript - the right way
January 31st, 2008Sometimes a programmer must do very weird things in his ASP.NET webapp. Among them, there is a postback initiated in custom javascript. Before .NET Framework 2.0, it was no good solution to achieve it. Fortunately it can be done without much effort nowadays.
There is an interface called IPostBackEventHandler which must be implemented by a page or a control. Then you must create javascript containing reference to postback function retrieved by ClientScriptManager.GetPostBackEventReference(...) method.
The sample web control's codebehind can look like below:
C#:
public class MyControl : Control, IPostBackEventHandler
{
// this method will be called on postback initiated in javascript
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument == "foo")
{
// do something
}
}
}
{
// this method will be called on postback initiated in javascript
public void RaisePostBackEvent(string eventArgument)
{
if (eventArgument == "foo")
{
// do something
}
}
}
then we create javascript in aspx / ascx file:
ASP:
<script>
function Test()
{
<%= Page.ClientScript.GetPostBackEventReference(this, "foo"); %>
}
</script>
function Test()
{
<%= Page.ClientScript.GetPostBackEventReference(this, "foo"); %>
}
</script>
Now, when a Test() function is called in a browser, our page will do a nice, clean postback ![]()

February 1st, 2008 at 10:40 am
Something’s weird in here. Namely, I don’t see connection between that class and script. How does ASP know that it should call MyControl.RaisePostBackEvent (and not SomeWeirdObject.RaisePostBackEvent)? Maybe ‘this’ in ASP is the answer but I rather suppose it’s a Page object…
February 1st, 2008 at 12:38 pm
Everything is ok. The javascript tag is embedded on MyControl.ascx
GetPostBackEventReference gets “this” as the control reference. If it was aspx (not ascx) the “this” reference would point to the page object.
I changed a post a little bit to make less confusion.