6

I'm building a site in MVC and the View Model I am passing to my View contains a custom object which in turn contains an IEnumarable list of custom objects.

The idea is that razor will dynamically generate the form for the IEnumerable which could be any number of objects.

@foreach (var data in Model.Kpi.Values)
{
   <div class="editor-label">
       @Html.Label(data.Field.Name);
   </div>
   <div class="editor-field">
       @Html.EditorFor(model => data.Value)
       @Html.ValidationMessageFor(model => data.Value)
   </div>
}

The forms display perfectly including the data annotations however the IEnumerable is null in the controllers post function.

[HttpPost]
public virtual ActionResult Create(KpiCreateViewModel vm)
{
    return this.RedirectToAction(MVC.Kpi.Index());
}

I've put a break point on the return statement and inspected the contents of the vm variable.

Can anyone suggest a method to retrieve the form data?

Thanks in advance

JConstantine
  • 3,980
  • 1
  • 33
  • 46

1 Answers1

4

It's because the EditorFor method doesn't have enough information to generate a name that can be used by the DefaultModelBinder when you post back. Look at the name attribute that is being generated in the HTML. The name is generated from the expression that you pass in, but you don't have to full path to the property in the loop.

Change it to an indexed loop and it should work.

@for(var i=0; i<Model.Kpi.Values.Count(); i++)
{
   <div class="editor-label">
       @Html.Label(model.Kpi.Values[i].Field.Name);
   </div>
   <div class="editor-field">
       @Html.EditorFor(model => model.Kpi.Values[i].Value)
       @Html.ValidationMessageFor(model => model.Kpi.Values[i].Value)
   </div>
}
Tim Rogers
  • 21,297
  • 6
  • 52
  • 68
  • Having said that, [this post](http://stackoverflow.com/questions/1983999/how-to-use-editorfor-inside-a-foreach) suggests that you can use `foreach`. But look at the name being generated and that should give you a clue. – Tim Rogers Jun 21 '11 at 16:40
  • That seems to have done half the battle. The object now has a value, but it doesn't have a Field.name. To clarify the KpiValue class has the properties, Field object, Kpi object, and Value string. Need some way of identifying the "Field". – JConstantine Jun 21 '11 at 16:44