-1

Sorry for the really nooby question, but this is tripping me up hard.

I have a controller Inspection, with method Configure which passes a model containing 3 lists. enter image description here

I know that I'm supposed to use HiddenFor to retain the information, but I don't know how to do this with lists.

enter image description here

I have these HiddenFor fields but they don't seem to work in retaining the information

@Html.HiddenFor(model => Model.inspection)
@Html.HiddenFor(model => Model.assignedParts)

for (int i = 0; i < Model.ConfigList.Count; i++)
{
    @Html.HiddenFor(model => Model.ConfigList[i])
}
Impulse
  • 155
  • 11
  • Why in the world would you degrade your app by generating a whole lot of hidden inputs, sending them to the view, and then sending them back to the controller unchanged. –  Dec 14 '16 at 07:54

1 Answers1

1

Every Razor directive gets converted into html to display in the browser. In this case, your directive for Model.assignedParts will probably look something like this in html:

<input type = "text" value="List<StevenHubs.Models.Part>" />

You can see exactly what it is by running your app and viewing the source. The text that is getting assigned to value is just Model.assignedParts.ToString(). The simplest way to fix your problem is to change your view to just use the pieces of the model that are actually getting changed.

If you want to include the list in your View, you will need to do a foreach over the list, and if the member of the list has properties, you will have to have a @Html.HiddenFor for each property so something like:

@foreach(var part in Model.Part) { @Html.HiddenFor(part.Property1) @Html.HiddenFor(part.Property2) }

murtuza
  • 1,129
  • 8
  • 7
  • Yeah I figured it would be something like this, was definitely hoping it could be just one simple thing haha. Thanks heaps! – Impulse Dec 14 '16 at 04:59
  • In case these solutions worked...http://stackoverflow.com/questions/9385286/html-hiddenfor-does-not-work-on-lists-in-asp-net-mvc – murtuza Dec 14 '16 at 05:02
  • You cannot use a `foreach` loop to generate form controls for a collection, and this cannot bind to a model (refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943)). Not to mention that code does not even compile –  Dec 14 '16 at 07:52