开发者

DefaultModelBinder and collections of complex types [duplicate]

This question already has answers here: Calling UpdateModel with a collection of complex data types reset all non-bound values? (3 answers) Closed 6 years ago.

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)


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜