Model binding generic list is null in asp.net mvc

前端 未结 1 988
后悔当初
后悔当初 2021-01-27 14:06

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

VIEW

@using (Ajax.BeginForm(\"Save\", \"Unit\", new AjaxOptions { OnSuccess =         


        
相关标签:
1条回答
  • 2021-01-27 14:26

    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>
    }
    
    0 讨论(0)
提交回复
热议问题