简体   繁体   中英

Event to save data in ViewState before postback

I am looking for an event firing before a DropdownList auto-postback to save Listbox items (populated with JS) in the ViewState.

I tried the OnSelectedIndexChanged event but it's fired too late.

Can this be done, and how?

This can't be done, using ViewState. ViewState is set by the server. It can't be modified by the client in JavaScript.

Suggest one of these options with JavaScript or jQuery:

  • modify a hidden input
  • modify a cookie value

You can then detect those changes after the page has posted back.

Set up your drop down to modify a hidden element.

$(document).ready(function() {
      $('#<%=DropDownList1.ClientID %>').change(function() { 

         $("#myHiddenInput").val("changed!");

      });
});

....
<input type="hidden" id="myHiddenInput" />

Your DropDownList will post back as per normal.

All of the following events happen before page load:

  • PreInit
  • Init
  • InitComplete
  • Preload

Take a look at the ASP.NET Page Lice Cycle to learn more.

LoadViewState happens in the Load cycle of the page so look at the events before that.

Also, have you looked into using the TrackViewState method? Might be just what you need in this situation...

Have you tried the OnChange event? take a look at this post
Update: Use a hidden field to pass custom data to server side. you cannot modify viewstate.
Also, there is a nice post by Scott Mitchell about this.

I know you've already marked an answer for this question, but I take it the reason you are asking is that your viewstate is failing validation because your listbox no longer contains the same options it did when the page is rendered? The simple answer would be to disable event validation on the page:

<%@ Page EnableEventValidation="false" %>

In your example, because you populated the listbox with x many items when the page was rendered, and you are adding items manually, ASP.NET kicks in and goes "hey, you've asked for option y that doesn't exist", and throws an exception accordingly.

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