The solution is to use the actual member name along with the desired data format string in the @Html.TextBoxFor
helper. Since the data is an IEnumerable simply place it in a for loop. The generated HTML will contain appropriate name field that matches the View Model's member name which is important for data persistence across POST backs. No hidden HTML form fields needed.
@for (int k = 0; k < Model.Currents.Count(); k++ ) {
@Html.TextBoxFor(model => model.Currents[k], "{0:F2}")
}
The above will work with proper data formatting. It generates
<input name="Currents[0]" id="Currents_0_" type="text" data-val-number="The field Double must be a number." data-val="true" value="0.8"/>
and works with proper persistence across POST backs.
The following three cases don't work:
case 1:
@foreach (double x in Model) {
@Html.TextBoxFor(m=>x, "{0:F2}")
}
- Does not persist across POST backs as it generates HTML with name="x".
- This one applies proper data formatting though.
case 2:
@Html.EditorFor(m => m.Currents)
- Does not data format as needed
- But persists across POST backs since actual view data member name is used in the generated HTML.
case 3:
@Html.EditorFor(m => m.Currents, "TemplateName")
Same as case 1.