.NET MVC Razor Dynamic Form Generation

2019-04-29 07:42发布

问题:

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

回答1:

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