DefaultModelBinder and collections of complex types [duplicate]

落花浮王杯 提交于 2019-12-25 02:15:50

问题


I have the following classes:

public class ComplexType
{
    public long? Code { get; set; }
    public string Name { get; set; }
}

public class TestViewModel
{
    public List<SubModel> List { get; set; }
    public ComplexType ComplexTypeTwo { get; set; }
    public string StringTwo { get; set; }
}

public class SubModel
{
    public ComplexType ComplexTypeOne { get; set; }
    public string StringOne { get; set; }
}

And the following controller action:

public ActionResult Index()
{
    var model = new TestViewModel
                {
                    List = new List<SubModel> { new SubModel{ComplexTypeOne = new ComplexType{Code = 1, Name = "One"}, StringOne = "String One"} },
                    ComplexTypeTwo = new ComplexType{Code = 2, Name = "Two"},
                    StringTwo = "String Two"
                }; 

    if (TryUpdateModel(model)) {} 

    return View(model);
}

Using this request:

/Home/Index?List[0].StringOne=updated&StringTwo=updated

Gives this result:

List[0].ComplexTypeOne: null
List[0].StringOne: "updated"
ComplexTypeTwo.Code: 2
ComplexTypeTwo.Name: "Two"
StringTwo: "updated"

As can be seen this results in ComplexTypeOne being set to null (which is different behaviour to ComplexTypeTwo). Is this expected behaviour? If so how best to maintain the previous values of complex types (and their properties) within the collection which are not included in the request?

(I asked a similar question 2 days ago but the example I posted (pre-editing) did not re-create the problem as I hadn't figured this only happens with collections)


回答1:


Found a previous post asking this exact question, which includes an override of the DefaultModelBinder which solves the problem:

Calling UpdateModel with a collection of complex data types reset all non-bound values?



来源:https://stackoverflow.com/questions/6957264/defaultmodelbinder-and-collections-of-complex-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!