我有一个模型如下所示:
public class TestViewModel
{
string UpdateProperty { get; set; }
string IgnoreProperty { get; set; }
ComplexType ComplexProperty { get; set; }
}哪里
public class ComplexType
{
long? Code { get; set; }
string Name { get; set; }
}我的主计长行动:
public Edit(int id, FormColleciton formCollection)
{
var model = service.GetModel(id);
TryUpdateModel(model);
//...
}在调用编辑操作时,我有一个formCollection参数,其中只包含UpdateProperty的键/值。
在正确设置了对TryUpdateModel UpdateProperty的调用之后,IgnoreProperty将保持不变,但ComplexProperty被设置为null,即使它以前有一个值。
TryUpdateModel()应该只修改作为请求一部分的属性吗?如果不是这样,那么只有当ComplexProperty包含在请求中时,才能最好地解决这个问题?
在Darin指出上面的测试用例没有演示问题之后,我添加了一个实际发生此问题的场景:
public class TestViewModel
{
public List<SubModel> List { get; set; }
}
public class SubModel
{
public ComplexType ComplexTypeOne { get; set; }
public string StringOne { get; set; }
}
public class ComplexType
{
public long? Code { get; set; }
public string Name { get; set; }
}主计长行动:
public ActionResult Index()
{
var model = new TestViewModel
{
List = new List<SubModel> {
new SubModel{
ComplexTypeOne = new ComplexType{Code = 1, Name = "5"},
StringOne = "String One"
}
}
};
if (TryUpdateModel(model)) { }
return View(model);
}发送此请求:
/Home/Index?List[0].StringOne=test更新SubModel.StringOne属性,但将ComplexTypeOne设置为null,即使它未包含在请求中。
这种预期的行为(如果不使用复杂类型的枚举就不会发生)吗?怎样才能更好地解决这个问题?
发布于 2011-08-02 15:42:53
您的测试用例一定有问题,因为我无法再现它。以下是我尝试过的:
模型(请注意,我使用公共属性):
public class TestViewModel
{
public string UpdateProperty { get; set; }
public string IgnoreProperty { get; set; }
public ComplexType ComplexProperty { get; set; }
}
public class ComplexType
{
public long? Code { get; set; }
public string Name { get; set; }
}主计长:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new TestViewModel
{
IgnoreProperty = "to be ignored",
UpdateProperty = "to be updated",
ComplexProperty = new ComplexType
{
Code = 1,
Name = "5"
}
};
if (TryUpdateModel(model))
{
}
return View();
}
}现在,我发送以下请求:/home/index?UpdateProperty=abc,在条件内部,只有UpdateProperty使用查询字符串中的新值进行修改。所有其他属性,包括复杂属性,都保持不变。
还请注意,FormCollection操作参数是无用的。
https://stackoverflow.com/questions/6914448
复制相似问题