Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attaching a hidden text field to a form MVC

This very well may end up being a very silly question in a way but basically I have this "form" in a model that gets attached to my View as the form but I haven't been able to actually pass any data do it from the View. It only has two properties: an Id property and a String property. I've been trying to fill the String property with text from a hidden text box on the page with no luck.

Form code:

    public class AllocateListForm
{
    public int Id { get; set; }

    public virtual string HiddenText { get; set; }
}

Relevant View code:

  <% using (Html.BeginForm("SaveExit", "User", new { }, FormMethod.Post, new { id = "selectExitPoints" }))  { %>
    <fieldset>
            <input type="hidden" id="HiddenText" />
    </fieldset>
  <% } %>

There is JQuery behind the scenes that fills HiddenText with text and I can assure you that it is filling. There is also JQuery behind the scenes that performs an Ajax submission and I can promise you that code works as it is used elsewhere in the application without a problem. When I perform the action that submits the form to the server and I go to my controller code that this points to, I have a breakpoint set so I can go into the console and check if the HiddenText field on the form has any data it is null. Can anybody point me in the right direction?

like image 572
Jfabs Avatar asked May 30 '13 12:05

Jfabs


People also ask

How do you use hidden fields in forms?

Definition and UsageThe <input type="hidden"> defines a hidden input field. A hidden field lets 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.


1 Answers

If you assign the input's name to be "HiddenText" the model binder should pick it up. I'm assuming that your controller action accepts an AllocateListForm as a parameter.

<input type="hidden" name="HiddenText" id="HiddenText" />

You can also use Html Helpers like so:

@Html.HiddenFor(model => model.HiddenText, new { id = "HiddenText" })

EDIT: Add an AllocateListForm as a property of your main model and then change the helper to be @Html.HiddenFor(model => model.MyAllocateListForm.HiddenText)

like image 183
Mansfield Avatar answered Sep 24 '22 03:09

Mansfield