Asp.net mvc disabled text field updated by javascript not publishing new value

I use a strongly typed model for my presentation. I have a disabled text field whose value I am updating with javascript. The text box is displayed using this

<%: Html.TextBoxFor(model => model.TotalAmount, new { disabled = "disabled"})%> 

This displays a text box with NAME and ID as "TotalAmount". TotalAmount is also a property of my model that binds to this view.

Javascript to update its value in the view, as it happens in its function:

 document.getElementById('TotalAmount').value = {assigning new value here}; 

The function calls the call, and I can see the value in the disabled text field when I change the value in another editable text field. However, when I submit this form to my action method, as shown below:

 [HttpPost] public ActionResult Process (ProcessVM FormPostVM) { } 

the property of the disabled text field [TotalAmount] still has the old value, but the changed text field that I changed contains the new value entered. Why doesn't the disabled text box contain an updated javascript value?

I tried to use

 ModelState.Remove("TotalAmount"); 

in the action method above, but, as I already thought, it does not work.

Any clues, clues?

Thank you for your time....

+6
source share
5 answers

HTML input elements, such as text fields that have the attribute disabled="disabled" , will never send their values ​​to the server when the form is submitted. If you want to send this value to the server and then disconnect the user from changing it, you can make the readonly text box:

 <%= Html.TextBoxFor(model => model.TotalAmount, new { @readonly = "readonly" }) %> 
+23
source

Disabled inputs are never submitted in the submit form, try using the readonly attribute or hidden inputs instead

+4
source

Disabled fields are not published. Try to have a hidden form field that sends the value to the server, and set both TotalAmount and the hidden form field. Instead, on the server, use the value for the hidden field.

On the side of the note, since it looks like the amount of the order, this is what I would count on the server, and not open the possibility of someone hacking html and get a discount on my product.

EDIT: Otherwise, I forgot about the readonly attribute. This will work too.

+4
source

If you change it to use readonly rather than disabled , then it will give you the same functions, but publish the value.

+3
source

Browsers do not publish values ​​in disabled input controls as you have discovered. Probably the easiest way to get around this is to connect to the form submission and re-enable input as the form; the user will not be able to change the value, and he should be sent with the rest of the request.

I think the last issue described this: please check this:

Retrieving an asp value: TextBox

+1
source

Source: https://habr.com/ru/post/914903/


All Articles