0

We can easily create a one-to-one relationship between a model simple properties of simple types like int, string, bool etc ... with <input> fields and checkbox fields in a view. Therefore, the content of those fields can be passed (or we can even keep track) back and forth between the controller and the view in POST request.

Now I have a List<MyObject> in my model. I tried to use @Html.HiddenFor<> to hold its or to populate it during POST but this does not do the trick.

I don't want to serialize anything. I thought ViewBag could help but ViewBag can't send data from the view to the controller (if I'm correct).

So what are the ways (beside serialization) to keep track of my model list in view and controller during POST requests ?

Bloomberg58
  • 157
  • 1
  • 16
  • Any state you want to persist to the page would need to be written to the page. And if you want that state returned in a form post then it would specifically need to be written as form elements. If serialization isn't an option then you'd need to drill into your models and create form fields for their individual value properties. – David Apr 21 '17 at 12:54
  • 2
    If the list doesn't change then don't post it back, post back a value that can be used to get the list (e.g. a parent id). If the list contents can change i.e. can be edited then create a `MyObjectModel` and it's own partial view and render it into your view. – Dave Becker Apr 21 '17 at 12:59
  • @David ya... And what would be a form field for `List<>` ? – Bloomberg58 Apr 21 '17 at 13:00
  • @Bloomberg58: It wouldn't be a single form field, that's the point. This answer looks helpful on the matter: http://stackoverflow.com/a/19965039/328193 – David Apr 21 '17 at 13:02
  • @DaveBecker Hmm can you elaborate on that ? `MyObjectModel` contains several properties. If I create a partial for it, it will have fields for each of them. Now since I'm dealing with a list of `List`, what would be the logic to hold each element of that list in the partial view ? – Bloomberg58 Apr 21 '17 at 13:04
  • See @David 's link it explains it better than I can. – Dave Becker Apr 21 '17 at 13:10
  • @DaveBecker Yes it does...Thanks guys. – Bloomberg58 Apr 21 '17 at 13:15
  • @David Thank you David. I'm glad you understood me. The answer will help me – Bloomberg58 Apr 21 '17 at 13:16

0 Answers0