Dynamic MVC Razor Dynamic Form Generation

I create a site in MVC, and the View model that I pass to my View contains a custom object, which in turn contains a list of IEnumarable custom objects.

The idea is that the razor will dynamically generate a form for IEnumerable, which can 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> } 

Forms render perfectly, including data annotations, however IEnumerable is null in the post controller function.

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

I set a breakpoint on the return statement and checked the contents of the vm variable.

Can anyone suggest a method to get the form data?

Thanks in advance

+6
source share
1 answer

This is because the EditorFor method EditorFor not have enough information to create a name that EditorFor can use when sending. Look at the name attribute that is created in HTML. The name is generated from the expression you pass, but you do not have the 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> } 
+2
source

Source: https://habr.com/ru/post/891033/


All Articles