Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 seeing the same thing.

Can someone explain why hidden form values are not being returned? Am I just doing this all wrong?

like image 390
JoeGeeky Avatar asked Mar 19 '12 19:03

JoeGeeky


People also ask

Which is correct about hidden form fields?

The <input type="hidden"> defines a hidden input field. A hidden field let web developers include data that cannot be seen or modified by users when a form is submitted. A hidden field often stores what database record that needs to be updated when the form is submitted.

What is hidden field in MVC?

Here we will learn how to create or use hidden fields in asp.net mvc with a simple example using HTML helpers. Before going in-depth, let's understand the definition of hidden fields. The hidden fields are controls that allow us to store data or information on a page without displaying it.


1 Answers

I just had the same problem. The form didn't submitted the hidden property because the model class didn't had a proper getter and setter for that property. I know that is not the issue you had, just figured it might help other people that will lend in this page.

like image 185
Ravid Goldenberg Avatar answered Sep 19 '22 06:09

Ravid Goldenberg