简体   繁体   中英

Firing Postback from Javascript

Ok, I know this question has been asked a lot and I've found plenty of information on the Web about this. Unfortunately, none of it really seems to work for me.

Basically, I have some JavaScript running in response to a user event. The JavaScript obtains a bit of information (an int) and then I want to get that back to the server.

The first approach was to use Page.ClientScript.GetPostBackEventReference to get a valid call to __DoPostBack() as described here .

I used this method to trigger a postback from a button. This seemed to be working except I get the error:

Invalid postback or callback argument. Event validation is enabled using 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.

Next, I tried to use a HiddenField's ValueChanged event handler. I wrote my handler, but changing the value of the hidden field does not trigger the event. Some form of postback still needs to be triggered somehow.

I don't really understand why I'm having so much trouble with this. Is there a more straight forward way of doing what I need?

Wow, no answers. Who would've thought this is so obscure.

Anyway, here's what worked for me. I just added an ASP.NET HiddenField to my form with a server-side handler for the ValueChanged event.

<asp:HiddenField ID="MyHidden" runat="server" OnValueChanged="MyHidden_ValueChanged" />

Then, in response to a user action, my JavaScript sets the value of this hidden field.

$('#<%= MyHidden.ClientID %>').val(myData);

And, finally, in order to trigger the hidden field's ValueChanged event, I initiate a postback with the following code. GetPostBackEventReference() returns a JavaScript statement, which will replace the server side markup.

<%= Page.ClientScript.GetPostBackEventReference(MyHidden, String.Empty) %>;

And it seems to work just fine. A postback occurs, and my ValueChanged handler is called. That handler determines the value of my hidden field and performs the required actions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM