Do Postback With Parameters in javascript

In this post i will show how to do a postback from a custom JavaScript function that emulates the click of an e.g. LinkButton. That is very simple to do so, but did you know that you also can send custom information via such a postback?


The following LinkButton calls the server-side event handler OnSaveClick.

<a<asp:LinkButton runat="Server" ID="btnSave" Text="Save" OnClick="OnSaveClick" />

This is pretty much standard and no tricks have been used so far. Now we need the
JavaScript method that forces the LinkButton to do a postback that calls the
server-side method OnSaveClick.

 <script type="text/javascript">

        function SaveWithParameter(parameter) {
            __doPostBack('btnSave ', parameter)


Notice that the function takes a parameter that it sends to the __doPostBack
function. All we need to do now is to call the SaveWithParamter function from

SaveWithParameter("Hello world!");

Now the page performs a postback and we can now access the “Hello world!” string
that we sent as a parameter from within the OnSaveClick event handler.

 protected void OnSaveClick(object sender, EventArgs e)

        string parameter = Request["__EVENTARGUMENT"];


What we just did was to perform a postback from a custom JavaScript function and
send a parameter to the server-side event handler. It sounds a lot harder than it
is, right?

In ASP.NET 2.0 you have to set the EnableEventValidation="false" attribute in the
page declaration or in web.config to make it work.

No comments:

Post a Comment