1

I am wondering how to properly use the HTML helper method HiddenFor when I am dynamically pulling in data to populate my view.

Prior to trying to use HiddenFor, I was using the regular hidden element using the following code:

@Html.Hidden("Answers["+i+"].FormEntryId", entry.FormEntryId)

This produces the following HTML:

<input id="Answers_0__FormEntryId" name="Answers[0].FormEntryId" type="hidden" value="d318afa2-42ba-4205-9f8a-9d7e6ad59ea4">

As you can see, it is quite fragile in that it relies on a string literal. Myself and another developer then decided to try and using HiddenFor as follows:

@Html.HiddenFor(x => x.Answers[i].FormEntryId, entry.FormEntryId)

This produces the following HTML, notice the empty value field:

<input data-val="true" data-val-required="The FormEntryId field is required." id="Answers_0__FormEntryId" name="Answers[0].FormEntryId" type="hidden" value="">

With x being a stand-in for our ViewModel. However, once we switched to this approach, we hit a snag where our id value is not populated what-so-ever. Thus, I am wondering, what is the correct way to use HiddenFor, and if it is even possible to do so when dealing with a dynamic view. The view model looks as follows:

johnnyRose
  • 6,243
  • 16
  • 40
  • 58
SomeStudent
  • 1,822
  • 1
  • 16
  • 25

1 Answers1

2

You are actually using wrong overload of HiddenFor helper method, you are already iterating on the Answers collection, you just need to use this overload which just takes expression as a single parameter like:

@for(int i=0; i<Model.Answers.Count; i++)
{
  @Html.HiddenFor(x => x.Answers[i].FormEntryId)
}

This will itself take care of generating correct id and name property of input elements so that their values are posted back in Model/ViewModel object back to controller action.

This should work for you fine.

SideNote:

If you have strongly typed view with a Model/ViewModel, you should always be using the Stringly Typed Helper Methods like TextBoxFor,HiddenFor,DropDownListFor etc instead of normal helper methods, as those require a little more work, and strongly typed ones will take care of posting back the new values for input elements via Form post.

Hope it helps!

Ehsan Sajjad
  • 59,154
  • 14
  • 90
  • 146
  • Thank you very much for the helpful pointer. However, in our case we need that id to be posted but it doesn't have that value. For us it is entry.formEntryId that has the value. We just dynamically associated answers[i].formEntryId with it. – SomeStudent Jul 17 '17 at 20:27