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?
Are you setting the
PageCountvalue in your POST controller action? If so make sure you have removed the old value from the ModelState: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.