ProfK
ProfK

Reputation: 51063

Why does a hidden input lose my view model's property value?

When I use the following Razor markup to try and send my PageCount value to the client, the value of the input is rendered as 0:

@using (Html.BeginForm("Index", "Gallery", FormMethod.Post, new { id = "search-form" }))
{
    @Html.HiddenFor(m => m.PageCount)

This renders as follows, despite PageCount having a value of 2:

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

When I fall right back on nearly all plain ol' HTML, like this:

<input type="hidden" name="PageCount" id="PageCount" value="2">

Is there some funny behaviour with Razor w.r.t. hidden inputs, or what?

Upvotes: 1

Views: 1821

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Are you setting the PageCount value in your POST controller action? If so make sure you have removed the old value from the ModelState:

[HttpPost]
public ActionResult Index(SomeViewModel model)
{
    ModelState.Remove("PageCount");
    model.PageCount = 2;
    return View(model);
}

The reason for this is that HTML helpers use the initially POSTed value when binding, not the one from the model. So you should remove the old value from the ModelState if you intend to modify it in your controller action.

And that's not only limited to HiddenFor helper. It's how all HTML helpers that generate input fields work.

Upvotes: 4

Related Questions