DefaultModelBinder和复杂类型的集合 [英] DefaultModelBinder and collections of complex types

查看:194
本文介绍了DefaultModelBinder和复杂类型的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

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; }
}

和下面的控制器动作:

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);
}

使用这个请求:

/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"

如可以看到这会导致ComplexTypeOne被设置为空(这是不同的行为ComplexTypeTwo)。这是预期的行为?如果是的话如何最好地维护复杂类型没有包括在请求中集合中的previous值(和它们的属性)?

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?

(我问过类似的问题 3天前,但这个例子我张贴(pre-编辑)做因为我已经没有想通不会重新创建这个问题只发生的集合)

(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)

推荐答案

发现了一个previous后问这个问题的准确,其中包括DefaultModelBinder的覆盖解决了这个问题:

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

<一个href=\"http://stackoverflow.com/questions/1207991/calling-updatemodel-with-a-collection-of-complex-data-types-reset-all-non-bound-v\">Calling的UpdateModel具有复杂数据类型的集合重置所有的非绑定值?

这篇关于DefaultModelBinder和复杂类型的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆