Model binding generic list is null in asp.net mvc

2019-03-06 02:47发布

I am binding objects in a razor foreach in the index.html:

VIEW

@using (Ajax.BeginForm("Save", "Unit", new AjaxOptions { OnSuccess = "onSuccess" }))
    {

<button type="submit" class="btn btn-default" id="saveUnits"><i class="fa fa-save"></i></button>


    <table>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>

                    @Html.HiddenFor(modelItem => item.UnitId)
                    <td>
                        @Html.EditorFor(modelItem => item.Name)
                    </td>
                    <td>
                        @Html.EditorFor(modelItem => item.ErrorText)
                    </td>

                </tr>
            }
        </tbody>
    </table>
}

I have grabbed the data sent to my action parameter with fiddler and got this:

item.UnitId=5&
item.Name=111111111111&
item.ErrorText=fsdddddddddddddddd+&

item.UnitId=5&
item.Name=+&
item.ErrorText=dddddd+&

ACTION

public ActionResult Save(List<Unit> units )
{
    return new EmptyResult();   
}

VIEWMODEL

public class Unit
{
    [HiddenInput(DisplayValue = false)]
    public int UnitId { get; set; }

    [DataType(DataType.MultilineText)]
    public string Name { get; set; }

    [DataType(DataType.MultilineText)]
    public string ErrorText { get; set; 
}

Why is my units instance null? The properties match so they should be bound!

Did I overlook something?

1条回答
Summer. ? 凉城
2楼-- · 2019-03-06 03:05

You need to use a for loop not a foreach loop. Also, it would be better to make your Model class have a property which is a collection.

Your model could be something like:

public class UnitsViewModel
{
    public List<Unit> Units { get; set; }

    public class Unit
    {
        [HiddenInput(DisplayValue = false)]
        public int UnitId { get; set; }

        [DataType(DataType.MultilineText)]
        public string Name { get; set; }

        [DataType(DataType.MultilineText)]
        public string ErrorText { get; set; }
    }
}

And you could do the following in your cshtml:

@for (int i = 0; i < Model.Count; i++)
{
    <tr>

        @Html.HiddenFor(m => m.Units[i].UnitId)
        <td>
            @Html.EditorFor(m => m.Units[i].Name)
        </td>
        <td>
            @Html.EditorFor(m => m.Units[i].ErrorText)
        </td>

    </tr>
}
查看更多
登录 后发表回答