Nested model binding

--- EDIT ---

I have this model

public class MainModel {
  string Name;
  List<Address> Addresses;
}

public class Address {
  string prop2;
}

      

It's easy to create a view, but I haven't found a way to bind it in the POST request. I would like to avoid looping on Request.Form

View

  @foreach (var obj in Model.Address)
  {
    <tr>
      <td>            
        <input type="text" id="@string.Format("obj.Name.{0}", obj.Id)" name="@string.Format("obj.Name.{0}", obj.Id)" value="@Model.Name" />
        //I'm not able to overwrite the name attribute, still working on that
      </td>
    </tr>
  }

      

Is there a way to automatically bind this list to the ActionController? Something like

public ActionResult Edit(MainModel model, List<Address> objects)

      

I am guessing that I need to create a custom model binding, but I have not found a way to do this

... MVC makes us lazy ... :)

+3


source to share


1 answer


From reading you requirements, you can think of a solution.

In the Views / EditorTemplates folder create an Address.cshtml view similar to

@model SampleMvc.Models.Address
    <tr>
        <td>
            @Html.HiddenFor(x=>x.Id)            
            @Html.TextBoxFor(x=>x.Prop2)
        </td>
    </tr>

      

Your edit window has markup similar to:

@using (Html.BeginForm()) {
    <table>
        @Html.EditorFor(x=>x.Name)
        <br/>
        <table>
            @Html.EditorFor(x=>x.Addresses)
        </table>
    </table>
    <input type="submit" id="submit" value="Submit"/>
}

      



The EditorFor will use the address editor template to render the label.

, ,

<tr>
   <td>
      <input id="Addresses_{HIGHESTIDVALUEHERE}__Id" type="hidden" value="{HIGHESTIDVALUEHERE}" name="Addresses[{HIGHESTIDVALUEHERE}].Id" data-val-required="The Id field is required." data-val-number="The field Id must be a number." data-val="true">
<input id="Addresses_{HIGHESTIDVALUEHERE}__Prop2" type="text" value="" name="Addresses[{HIGHESTIDVALUEHERE}].Prop2">
   </td>
</tr>

      

public ActionResult Edit(MainModel model){
}

      

+4









All Articles