を処理するために形成するために、親オブジェクトのIDを渡す:デザインパターン:どのようにHttpPostは、クラス階層を以下に私が持っている
public class Parent
{
public int ID {get;set;}
public string SomeOtherProperty {get;set;}
...
public virtual ICollection<Child> Children {get;set;}
}
public class Child
{
public int ID {get;set;}
public string SomeChildProperty {get;set;}
...
public virtual Parent Parent {get;set;}
}
pubic class ViewModel
{
public ICollection<Parent> Parents {get; set;}
public NewChildVM ChildToAdd {get;set}
}
public class NewChildVM
{
public int ParentID {get; set;}
public string SomeChildProperty {get; set;}
}
基本的にViewModelには、子オブジェクトのコレクションを持っているそれぞれの親オブジェクトのコレクションであり、 。私はまた、ビュー内のフォームを移入するために使用されるプロキシの子オブジェクトを渡したいと思います。ビューは、ヘッダーの詳細を含むParentオブジェクトをループし、入力用のフォームを表示し、親の子オブジェクトのリストを表示します。
foreach(Parent Prnt in Parents)
{
@Html.BeginForm()
{
<fieldset>
<legend>new message:</legend>
@Html.LabelFor(x => x.ChildToAdd.SomeChildProperty)
@Html.EditorFor(x => x.ChildToAdd.SomeChildProperty)
@Html.HiddenFor(x => x.ChildToAdd.ParentID, new { Value = Prnt.ID.ToString() })
</fieldset>
<input type="submit" value="SEND"/>
}
foreach(Child Chld in Prnt.Children)
{
... do the html for the child listing
}
}
私はParentIDをフォームに入力するのが苦労しています。 @Html.HiddenForを使用すると、 'Value'属性を設定することはできませんが、メソッドのHttpPostバージョンにNewChildVMを渡すと自動的に読み込まれません。
私はこれにアプローチする2つの方法があると思います。最初は、VMの一部としてNewChildVMのコピーが1つあるところです。その場合、どのようにして'value'は実際のビューのフォームに表示されます。もう1つの方法は、Parentを継承し、NewChildVMをParentVM内のプロパティに移動するParentVMを作成することです。つまり、Parentのインスタンスに関連付けられていることを意味します。これが方法に近づけば、ViewModelのParentVM.IDを使ってNewChildVM.ParentIDをどのように設定するのですか?