asp.net mvc disabled text box updated by javascrip

2019-04-28 13:55发布

问题:

I am using a strongly typed model for my view. I have a disabled text box whose value I update using javascript. The textbox is rendered using this

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

This renders a textbox with NAME and ID as 'TotalAmount'. TotalAmount is also a property on my model that binds to this view.

The javascript to update its value in the view is like this within its function:

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

The function does get called and I can see the value in the disabled textbox when I change some value in another editable textbox. However, when I post this form to my action method as below :

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

the disabled textbox property [TotalAmount] still has the old value but the editable textbox which I modified contains the new value I entered. Why does the disabled textbox not contain the javascript updated value?

I tried using

ModelState.Remove("TotalAmount");

in the action method above, but as I already figured it didn't work.

Any clues, tips?

Thanks for your time....

回答1:

HTML input elements such as textboxes that have the disabled="disabled" attribute will never send their values to the server when the form is submitted. If you want to send the value to the server while still disabling the user from changing it you could make the textbox readonly:

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


回答2:

Disabled inputs are never sent in a form submit, try using readonly attribute instead or hidden inputs



回答3:

Disabled fields don't get posted. Try having a hidden form field that will send the value to the server, and set both TotalAmount and the hidden form field. On the server, use the value for the hidden field instead.

On a side note, since this looks like the order total, this is something I would recalcuate on the server rather than opening up the possibility of someone hacking the html and getting a discount on their product.

EDIT: To the other's points, I'd forgotten about the readonly attribute. That will work too.



回答4:

If you change it to use readonly rather than disabled, then this should give you the same functionality, but post the value.



回答5:

Browsers don't post values back in disabled input controls, as you've discovered. Probably the easiest way to work around this is to hook onto form submission, and re-enable the input as the form is being submitted; the user won't have a chance to edit the value, and it should get posted with the rest of the request.

i think the last issue described it : please check it out :

Retrieving the value of a asp:TextBox