views:

760

answers:

5

I have some client-side JavaScript that sets form fields. When the page posts back, those fields are reset.

Why is this? Aren't the field values captured and put in the ViewState when the postback occurs?

EDIT: When I break the debugger on Page_Load(), before any code executes after the postback, the form field values are empty.

+1  A: 

Yes. It sounds like you have something else going wrong (perhaps an OnLoad handler that isn't checking the IsPostback field and therefore overwriting your changed values?).

jsight
+1  A: 

Check what is being initialized on server side, the most common issue that I have seen is that any server side initialization code doesn't check for IsPackBack like so:

if (!Page.IsPostBack) {

    // Do Work

}
Jon Erickson
A: 

The other thing to check is whether you are doing a postback or a callback. If you're doing a callback, the form field values sent back with the callback are the ones the page first sent to the client. For some reason ASP.NET AJAX pickles these values and sends them with every callback, instead of reading the form field afresh.

Sebastian Good
+4  A: 

Are the form elements that are being populated from your client-side javascript set as disabled? If so, ASP.NET will ignore the value.

For example:

<asp:TextBox ID="TextBox1" Enabled="False" Runat="Server" />

<script type="text/javascript">
    document.forms[0].elements["TextBox1"].style.disabled = false;
    document.forms[0].elements["TextBox1"].value = "Value set from Javascript";
</script>

When this code runs, ASP.NET thinks that the textbox is disabled, and therefore discards its value in the postback, so the value of TextBox1.Text will always be blank. As far as I know, this behavior applies to all form elements. If ASP.NET thinks they are disabled, and they are subsquently enabled and populated client-side, the value won't be available on the postback.

Mun
Nice catch. Took me a little while to figure this out. :)
Chris
A: 

It's because I had enabled="false" set on the fields. I changed the fields to readonly="true" and the same thing happens.

The solution was to change the fields to readonly at runtime using JS.

Chris