説明したように、AとBを使用できるはずです。
次のものがあるとします。
public class B {
public A A {get; set;}
public string X {get; set;}
public int Y {get;set;}
}
public class A {
public string Z {get; set;}
}
//then in your controller:
public ActionResult Edit () {
return View (
new B {
A = new A { Z = "AyyZee" } ,
X = "BeeEcks",
Y = 7
} );
}
したがって、モデルはBのインスタンスです。
ビューとネストされた部分ビューは、次のようなHTMLを生成する必要があります。
<input type="text" name="A.Z" value="AyyZee" />
<input type="text" name="X" value="BeeEcks" />
<input type="text" name="Y" value="7" />
これで、デフォルトのモデルバインダーがこれを接続できるようになります。
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Edit (B input) {
// apply changes
//the binder should have populated input.A
}
これは、AとBの両方にデフォルトのコンストラクターがあり、比較的単純なクラスである場合にのみ機能することに注意してください。より複雑なものがある場合は、独自のバインダーを使用できます。
[AcceptVerbs( HttpVerbs.Post )]
public ActionResult Edit ( [ModelBinder( typeof( BBinder ) )] B input) {
//...
}
public class BBinder : IModelBinder
{
public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
{
return
new B {
A = new A { Z = Request["A.Z"] } ,
X = Request["X"],
Y = int.Parse(Request["Y"])
};
}
}