Model binding generic list is null in asp.net mvc

前端 未结 1 989
后悔当初
后悔当初 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 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++)
    {
        
    
            @Html.HiddenFor(m => m.Units[i].UnitId)
            
                @Html.EditorFor(m => m.Units[i].Name)
            
            
                @Html.EditorFor(m => m.Units[i].ErrorText)
            
    
        
    }
    

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