0

I am able to return a view to a user with a list of entities, but in that view I'd like to have a form in which each entity can be edited individually and when the user submits the form I will receive all of the entities back.

addresses = entities.Addresses.Where(m => m.CountryId == null);
return View(addresses);

This brings all the items into the view which I manage with

@foreach (var item in Model) {

My issue is that I don't know where to begin in forming an action result that is triggred from form submit and carriers all the items (and changes) back with it. I am able to do this easily with 1 single item on a view, but stumped when I have a list of them.

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
nextint
  • 81
  • 2
  • 6

1 Answers1

0

If you are using straight up MVC, then doing the batch update operation will get pretty hairy because of the limitations of form elements. Here is a rough sketch of something you can do:

<form action="/mypage">
@foreach(var item in Model) {
   <input type="text" name="property1-@item.uniqueID" />
   <input type="text" name="property2-@item.uniqueID" />
}
</form>

This approach is messy because when posted back to your action method, MVC's default model binding is not going to be smart enough to associate property1 and property2 with the same object in some sort of list, and you'll probably have to do that manually by going through the form fields in the HttpContext.Request.Form collection.

This can be made easier by using JSON and some javascript, but it muddies some of the client side code as a result. Consider:

<form action="/mypage">
<input type="hidden" 
    name="itemsSerialized" 
    value="JsonConvert.Serialize(Model.Items)" />
@foreach(var item in Model.Items) {
   <input type="text" name="property1-@item.uniqueID" />
   <input type="text" name="property2-@item.uniqueID" />
}
</form>
<script type="text/javascript">
    // write some js code that every time an input is modified for a property, 
    // update the serialized string in the itemsSerialized hidden input
</script>

The advantage to the second method is that your action method becomes much simpler, it takes in a (List<Item> itemsSerialized) as its parameters, and MVC model binding should be smart enough to correctly turn it into a list.

Another advantage of the second one is that you will probably be able to turn it into an API-based ajax page instead of relying on POSTS, if that's what you ultimately want.

welegan
  • 3,013
  • 3
  • 15
  • 20