Problem solve Get help with specific problems with your technologies, process and projects.

How do I properly save data in controls that were populated by JavaScript?

I have a complicated Web form that has many controls on it. I am using a popup window that is opened with JavaScript to fill in a textbox and a listbox to be returned to the parent page. When I use JavaScript to fill in textbox and listbox controls, only the textbox data is saved on postback. How would I go about properly saving data in controls that were populated by JavaScript? I've even tried debugging to see what is in the request.form object for those controls and they are empty!
ASP.NET uses a mechanism called ViewState to "remember" control values between postbacks. This state is stored in a hidden field in the page, and processed each time the form is posted. That's why you get the listboxes (loaded on the server-side) rendered automatically with all the items. But only the ViewState is posted back, together with the current value of form controls. As you're loading these values on the client-side, the __VIEWSTATE hidden field doesn't contain any information about it, and so they are lost when the form comes back.

One workaround is to use another hidden field and persist manually your listbox items (i.e. in a comma-separated list). You'll get this value back upon a postback, and you can repopulate the control from it from your JavaScript again.

Dig Deeper on Win Development Resources

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.