1

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?

Spilarix
  • 1,418
  • 1
  • 13
  • 24

4 Answers4

2

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.

p.campbell
  • 98,673
  • 67
  • 256
  • 322
1

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...

Abe Miessler
  • 82,532
  • 99
  • 305
  • 486
0

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.

Community
  • 1
  • 1
Kamyar
  • 18,639
  • 9
  • 97
  • 171
  • I can't use a JS event like "OnChange" because I need to save to the ViewState (server side)... – Spilarix Oct 14 '10 at 16:20
  • Well, I think you going in the wrong direction. **EVERY** method in the code behind, will be fired **after** the postback. Actually, it doesn't make any sense to say that you want to fire a method in the code behind before postback. You have to use JS to be able to call methods before postback. – Kamyar Oct 14 '10 at 16:24
  • 1
    Doing something on the server side before you do a postback is like cooking bacon for breakfast while you are still in bed. (unless you are using ajax but I don't think that applies in this question) – Abe Miessler Oct 14 '10 at 16:25
0

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.

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129