3

---EDIT---

I have this model

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

public class Address {
  string prop2;
}

Is quite easy to create the view but I didn't find a way to bind it in the POST request. I would like to avoid to loop 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 in the ActionController? Something like

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

I suppose I have to create a custom model binding but I don't find the way to do it

... MVC make us lazy ... :)

Davide
  • 1,305
  • 3
  • 16
  • 36

1 Answers1

4

From reading you're requirements you may be over thinking the solution.

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

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

In your Edit view have 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 statement will use the Address editor template to render the mark up.

If you need the ability to add new addresses you can use client side scripting to find the highest id and inject the following mark up

<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>

Then you controller action becomes

public ActionResult Edit(MainModel model){
}
heads5150
  • 7,263
  • 3
  • 26
  • 34
  • Thanks, this is for sure the way (here I also found a full example: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx if somebody else need it). – Davide Jan 24 '13 at 07:38