asp.net - MVC model binding to nested collection

后端 未结 1 1435
青春惊慌失措
青春惊慌失措 2021-01-06 20:36

I have a class:

public class ClientInformation{
    public string UserName {get; set;}
    public ICollection RegionDistrictCity
           


        
相关标签:
1条回答
  • 2021-01-06 20:48

    In MVC4 you should use a for loop instead of a foreach to bind your collection. Then the model binder will be able to populate your model when you submit your data.

    @for (int i = 0; i < Model.RegionDistrictCity.Count; i++)
            {
                @Html.EditorFor(model => Model.RegionDistrictCity[i].Region)
            }
    

    But this will only work if you are not deleting or adding items to your collection dynamically. If you want to do that, you should use the BeginCollectionItem helper created by steve sanderson. http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

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