0

My existing view contains model binding.

@model Catalog.Models.SomeModel

Now, i need to extend my "SomeModel" to contain a list of data "ListData". Binding these data would be fine, where i will use foreach to display the data.

@foreach(var element in Model.ListData) {
    //do as needed...
}

The enhancement now i need to do is make the the controls populated in the foreach loop dynamic. Where i can add/remove a row of data. Basically, when i will add a new row, a new ListData object should be added to the list and accordingly for remove. For template i am planning to use Moustache.js.

For saving the data, right now Post is used which sends the model back to the action method. Now, i have the following doubts:

  1. Can i modify the listData and post the model just like it is being done right now? If yes how?
  2. Do i need to replace the current post approach and hit the action directly using javascript?
Harsh
  • 3,683
  • 2
  • 25
  • 41
  • And for a more complete example using `BeginCollectionItem` refer [this answer](https://stackoverflow.com/questions/40539321/a-partial-view-passing-a-collection-using-the-html-begincollectionitem-helper/40541892#40541892) –  Aug 14 '17 at 06:15
  • Thanks @StephenMuecke Partial view was something i did not think about till now. Let me take a look in that direction. – Harsh Aug 14 '17 at 06:16
  • @StephenMuecke My collection is part of the main model which is being bound right now. So, my main view will be bound to that and the partial view to the collection of that main model. Is that right? And on post the updated model will be returned? – Harsh Aug 14 '17 at 06:26
  • 1
    The partial will be `@model ListData` The key to dynamically adding and deleting items is to create an additional `` where `#` is the same as the indexer for the property (see also [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943)). The `BeginCollectionItem` method does all that for you. –  Aug 14 '17 at 06:30
  • 1
    The alternative is to use a client side template and just javascript (no ajax calls required so better performance but a bit harder to maintain - its not strongly typed to your model) –  Aug 14 '17 at 06:31

0 Answers0