我一直在研究一个 MVC 项目,该项目具有一个带有多个嵌套类的复杂模型,一个类中嵌套了另一个类。我可以让所有其他复杂类型正确更新,但最后一个永远不会正确更新。我已确保注册其自定义模型绑定器,该绑定器会被执行并返回一个对象,该对象具有分配给其属性的正确值,但原始模型永远不会更新。
我已经剪掉了所有有效的东西,只剩下我的结构:
课程
public class Case
{
public Case()
{
PersonOfConcern = new Person();
}
public Person PersonOfConcern { get; set; }
}
[ModelBinder(typeof(PersonModelBinder))]
public class Person
{
public Person()
{
NameOfPerson = new ProperName();
}
public ProperName NameOfPerson { get; set; }
}
[TypeConverter(typeof(ProperNameConverter))]
public class ProperName : IComparable, IEquatable<string>
{
public ProperName()
: this(string.Empty)
{ }
public ProperName(string fullName)
{
/* snip */
}
public string FullName { get; set; }
}
模型粘合剂
public class PersonModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof(Person))
{
HttpRequestBase request = controllerContext.HttpContext.Request;
string prefix = bindingContext.ModelName + ".";
if (request.Form.AllKeys.Contains(prefix + "NameOfPerson"))
{
return new Person()
{
NameOfPerson = new ProperName(request.Form.Get(prefix + "NameOfPerson"))
};
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
控制器
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
if (CurrentUser.HasAccess)
{
Case item = _caseData.Get(id);
if (TryUpdateModel(item, "Case", new string[] { /* other properties removed */ }, new string[] { "PersonOfConcern" })
&& TryUpdateModel(item.PersonOfConcern, "Case.PersonOfConcern"))
{
// ... Save here.
}
}
}
我无计可施。被PersonModelBinder
执行并返回正确的值集,但模型永远不会更新。我在这里想念什么?