问题
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