views:

200

answers:

1

I tried numerous times over the last few weeks to get a server side MVC 2 view to work with objects with nested IList elements without much success. I am missing some fundamental understanding that I hope this question resolves.

What I want is a form that shows a list of product where you can change information in-line, including a hierarchy (a list of product that each has a list of sub-products, that each has a list of images, etc.) I am trying to recreate an older MS Access form where the big form has a list of products and sub-forms show the related products, all allowing in-line edits. Access saves each record upon focusing on a different record.

Say you have a Domain Model that looks like this:

public class Product {
    ... // Lots of fields like public string name {get; set;}
    public IList<Department> departments {get; set;}
    public IList<SubProduct> subProducts {get; set;}
}
public class SubProduct {
    ... // Lots of fields like public string name {get; set;}
    public IList<Image> images {get; set;}
}
public class Image {
    ... // Lots of fields like public string name {get; set;}
}

And a view Model that looks like this:

public class EditProduct {
    IList<Product> products {get; set;}
}

In the MVC 2 View, how would you code the Edit fields so that you can post the single model back to the controller? I am familiar with the

<input id="products[0].subProducts[0].images[0].name" /... >

mechanic, but each IList needs a way to CRUD elements on the same screen. It's a big data entry screen where speed counts as much as being able to see all products in a list. I need Add buttons, Delete buttons, and a means to post the entire form after editing any inputs.

If I look at it from a JQuery point of view:

  • I serialize the Model as JSON for the initial form for the first N number of IList elements
  • I load on the fly additional products in the same list when they reach the bottom of the container div
  • I accept the entire Model upon save/post or accept pieces of the same form for individual entities, like having a separate html form tag for each IList element

But for some reason, I am just not getting how to do this at the server side. Any links or example code for the View itself would be great. Elements without IList seems to work great, especially with UI templates. Would I create a bunch of individual html form tags around each editable entity and have posts only deal with one element at a time?

A: 
<% for (int count = 0; count < Model.Students.Count; count++ )
   {                                              %><%= 
      Html.EditorFor(m => m.Students[count])      %><%
   } 
%>

Creates form names like:

name="Students[0].Name"
name="Students[1].Name"
name="Students[2].Name"

Which bind back to the original List view model

Dr. Zim