views:

40

answers:

1

If I have an object that is composed of nested complex types, e.g. a ViewModel that has a List<Fu> and a List<Bar>

public class WarViewModel
{
    List<Fu> Fu { get; set; }
    List<Bar> Bar { get; set; }
}

public class Fu
{
    public int Id {get;set;}
    public Soldier Private { get; set; }
}

public class Bar
{
    public int Id {get;set;}        
    public Soldier Private { get; set; }
}

public class Soldier
{
    public int Id {get;set;}
    public string Name { get; set; }
    public int Age { get; set; }
}

if I had a form that contained 2 select lists, either with Fu or Bar, where each option represented each soldier in the list, and the option had attributes containing Id, Name and Age, such as

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<WarViewModel>" %>

<% using (Html.BeginForm("WarAction", "War")) { %>        
    <% foreach (var soldier in Fu) %>
        <select class="fu">
            <option id='<%= soldier.Id %>' age='<%= soldier.Age %>'><%= soldier.Name %></option>
        </select>
    <% } %>

    <% foreach (var soldier in Bar) %>
        <select class="bar">
            <option id='<%= soldier.Id %>' age='<%= soldier.Age %>'><%= soldier.Name %></option>
        </select>
    <% } %>        
<% } %>

What naming convention do I need to use so that when the form is submitted, the following action method's WarViewModel will be populated with the soldiers that are selected in both lists?

public ActionResult WarAction(WarViewModel war)
{
    return View();
}

My understanding now is that the model binder won't know soldier is which, so it won't know which Id is associated with which soldier. Is there a way for me to work around this? I know that the code above won't validate but I'm trying to implement a proof of concept for myself.

Also, what needs to be changed to make this approach RESTful?

+1  A: 

What your trying to do is already supported:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

jfar