Alex Rivera | Logout

Hidden form fields not appearing in MVC Model after post-back

Asked 2012-03-19T19:06:19.497
14

I have a new MVC 4 Application with a fairly basic View/Controller. The associated Model contains a couple properties that I've mapped to Hidden form fields. When the Page renders the first time (e.g. via the HttpGet Action) it all looks fine. But when the form is Post'ed by selecting the Submit button the resulting Model presented to the Action no longer has the Hidden field values set. Here is a walkthrough of the particulars.

Here is a sample of the Model:

public class Application
{
    public bool ShowSideBars { get; set; }
}

Here is the initial Controller *Action* (which seems to work fine):

[HttpGet]
public ActionResult Application()
{
    var model = Request.ParseFromQueryString<Application>();
    model.ShowSideBars = true;

    return View(model);
}

This maps to the View as follows:

<fieldset>
    @Html.HiddenFor(m => m.ShowSideBars)
...
</fieldset>

This results in the following mark-up to be rendered inside the fieldset:

<input data-val="true" data-val-required="The ShowSideBars field is required." id="ShowSideBars" name="ShowSideBars" type="hidden" value="True" />

Note: I sure wish I knew why MVC has decided to add the '... field is required' content when I didn't flag it as required, but that's for another question

Here is the Action that is called when the form is submitted. At this point the aforementioned property will no longer be set to 'true'.

[HttpPost]
public ActionResult Application(Application application)
{
    // Other work done here

    return View(application);
}

At present, there are no custom Model Binders. Also, I've tested some other data types and I'm s

Edit
Report

1 Answer

10

If you have the property in your model decorated with a ReadOnlyAttribute the value will not be populated back into the model for you. After all, it is read only.

answered 2012-10-12T19:17:24.903

Your Answer