0

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.

5 Answers 5

4

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.

1
  • Nice catch. Took me a little while to figure this out. :)
    – core
    Apr 21, 2009 at 0:11
1

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

1

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

}
0

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.