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: