私は、いくつかのネストされたクラスを持つ複雑なモデルを持つ MVC プロジェクトに取り組んでおり、1 つのクラスに別のクラスがネストされています。他のすべての複合型を正しく更新できますが、この最後の複合型は正しく更新されません。カスタム モデル バインダーを登録したことを確認しました。これは実行され、プロパティに適切な値が割り当てられたオブジェクトを返しますが、元のモデルは更新されません。
機能するものはすべて切り取って、構造のみを以下に残しました。
クラス
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
が実行され、正しい値のセットが返されますが、モデルは更新されません。ここで何が欠けていますか?