ASP.NET MVC 5 model binding list is empty

后端 未结 1 684
粉色の甜心
粉色の甜心 2020-12-11 16:53

I stuck on this issue for a while..

I\'ve created a simple view model:

public class AddTranslationViewModel
{
    public List

        
相关标签:
1条回答
  • 2020-12-11 17:26

    Binding to a list of object requires creating input field structure with names containing indexes, i.e:

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

    Moreover, you need to point the form to the proper Action Method in your Controller using Razor's Html.BeginFrom method (see documentation). In you 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 edit, but CREATE method, then obviously your List in model will have 0 elements. In this case, change the stop condition in for loop to desired count.

    Keep in mind that this topic was discussed many times before:

    ASP.NET MVC bind array in model

    ASP.NET MVC - Can't bind array to view model

    0 讨论(0)
提交回复
热议问题