4

I have a form with the autocomplete attribute set to off.

Inside this form, there is a hidden input element (generated using ASP.NET MVC's Html.HiddenFor() method, but, that should be irrelevant):

<input type="hidden" value="0" name="Status" id="Status" data-val-required="The Status field is required." data-val-number="The field Status must be a number." data-val="true">

When the form is submitted, this value is incremented by one and the model is returned to the view. If I write the status value to the page, I can see that the value was correctly incremented.

However, this hidden input field is always cached. It's never getting the correct value. I tried setting the autocomplete attribute directly on the input element, but without success.

How can I get this hidden field to get the correct value? I'd prefer not to use any Javascript.

Edit: Supplying more code...

Controller

//This code is being executed, and the status is being incremented.
shippingOrder.Status = (shippingOrder.Status != (int)OrderStatus.Closed) ? shippingOrder.Status + 1 : shippingOrder.Status;

View

@using (Html.BeginForm("Number", "Order", FormMethod.Post, new { id = "orderSummary", autocomplete = "off" })) {
    ...
    @Html.HiddenFor(m => m.Status)
}
Justin Helgerson
  • 24,900
  • 17
  • 97
  • 124
  • How about posting your controller actions, specifically the part where it is incremented, and maybe the views? – Aaron Daniels May 08 '12 at 22:01
  • @AaronDaniels - I didn't want to make the question too specific to my scenario, but I did add some code samples. I've tested this with other properties as well, such as a string. I've tried hard-coding in a value in the controller and the hidden input still doesn't get updated, but if I write the value to the HTML response I see the value that I want. The model *is* getting the correct value. – Justin Helgerson May 08 '12 at 22:10

1 Answers1

3

According to this post here html helpers such as HiddenFor will always first use the posted value and after that the value in the model.

As you said, when writing the value to the page you can see it incremented, yet the helper is using the previously posted value, which is the intended behaviour.

The link does suggest the use of ModelState.Remove("Status") or ModelState.Clear() before assigning the new value.

It also suggest that another option could be not using a HiddenFor helper but instead to build the hidden field yourself. Similar to this:

<input type="hidden" name="Status" value="@Model.Status" />

Either way it looks like your problem is based on similar circumstances.

Community
  • 1
  • 1
Nope
  • 22,147
  • 7
  • 47
  • 72
  • Thanks for your help. I'd prefer not to hard code property names with strings, so I'm going to use the `Clear()` method to solve this. – Justin Helgerson May 09 '12 at 14:25