ASP.NET MVC 5 model binding list is empty

I am stuck on this issue for a while.

I created a simple view model:

public class AddTranslationViewModel { public List<ProjectTranslation> ProjectTranslations { get; set; } public AddTranslationViewModel() { ProjectTranslations = new List<ProjectTranslation>(); } } 

ProjectTranslation Class:

 public class ProjectTranslation { public int ProjectTranslationId { get; set; } public string Title { get; set; } public string Description { get; set; } public string Address { get; set; } public int LanguageId { get; set; } public Language Language { get; set; } public int ProjectId { get; set; } public Project Project { get; set; } } 

A simple view that uses AddTranslationViewModel

 <table class="table"> @foreach (var item in Model.ProjectTranslations) { @Html.HiddenFor(modelItem => item.ProjectTranslationId) <tr> <td> @Html.DisplayFor(modelItem => item.Language.LanguageCode) </td> <td> @Html.EditorFor(modelItem => item.Title) </td> </tr> } </table> <input type="submit" value="Send" /> 

and finally my POST method:

  public ViewResult AddTranslation(AddTranslationViewModel projectTranslations) { if (ModelState.IsValid) { //... } return View(projectTranslations); } 

The idea is very simple, I want to show a list of elements where it should be possible to change / change the values.

However, model binding does not work; the projectsTranslations parameter in the HTTPTost AddTranslation method is always empty.

What is the mistake here?

+6
source share
1 answer

Binding to a list of objects requires creating an input field structure with names containing indices, that is:

 <input type="text" name="YourArrayOrList[0].SomeProperty" value="123" /> <input type="text" name="YourArrayOrList[0].SomeOtherProperty" value="321" /> <input type="text" name="YourArrayOrList[1].SomeProperty" value="123" /> <input type="text" name="YourArrayOrList[1].SomeOtherProperty" value="321" /> 

In addition, you need to specify the form with the correct action method in your controller using the Razor Html.BeginFrom method ( see the documentation ). In this case, it should look like this:

 @using(Html.BeginForm("AddTranslation","YourControllerName")) { for (int i=0;i<Model.ProjectTranslations.Count; i++) { @Html.HiddenFor(model => model.ProjectTranslations[i].ProjectTranslationId) <tr> <td> @Html.DisplayFor(model => model.ProjectTranslations[i].Language.LanguageCode) </td> <td> @Html.EditorFor(model => model.ProjectTranslations[i].Title) </td> </tr> } } 

If your method is not edited, but the CREATE method, then, obviously, your list in the model will contain 0 elements. In this case, change the stop condition in the for loop to the desired count.

Keep in mind that this issue has been discussed many times:

ASP.NET MVC Binding Array in Model

ASP.NET MVC - Unable to bind array to view model

+6
source

All Articles