ビューモデルはいつ使用する必要がありますか?ドメインの使用はお勧めしませんか?ビューモデルがドメインオブジェクトのコピーであり、値が表示されないことがわかりました...
ビューモデルを常に使用する必要があります。ビューでドメインモデルを使用しないでください。
ビューモデルは、ドメインモデルの正確なコピーではありません。ビューの特定の要件に関連するいくつかの違いが常にあります。たとえば、ある画面ではドメインモデルのプロパティの一部を表示し、他の画面では他のプロパティを表示したいとします。これの結果として、1つのプロパティが1つの画面で必要になり、他の画面では必要とされないため、さまざまな検証要件もあります。したがって、これらのビューモデルにもさまざまなデータ注釈があります。
いつパーシャルを使用する必要がありますか?部分ビューを再利用する場合のみですか?
ビューが再利用される場合だけではありません。パーシャルを使用して、ビューをより構造化することができます。また、AJAXを使用している場合は、パーシャルを使用すると簡単になります。AJAXリクエストをコントローラーアクションに送信すると、DOMの一部のみを更新できる部分的なビューが返されます。
表示テンプレートとエディタテンプレートはいつ使用する必要がありますか?ビューモデルなしでこれらを使用できますか?
いつも。強く型付けされたモデルで使用できますが、常にビューモデルを使用する必要があります(前の質問への回答を参照)。
親オブジェクトと子オブジェクトのリストの両方を編集できる編集画面を作成するにはどうすればよいですか?つまり、上部のいくつかのフィールド(親)と下部のフィールドのグリッド(編集可能な行など)、特に、バインディングを行うにはどうすればよいですか?automapperは使用されません。
これはかなり広い質問ですが、いつものように答えるには、編集のためにこの画面に表示したいプロパティを表す/含むビューモデルを定義することから始めます。
public class ChildViewModel
{
[Required]
public string Name { get; set; }
}
public class ParentViewModel
{
[Required]
public string Name { get; set; }
public IEnumerable<ChildViewModel> Children { get; set; }
}
次にコントローラー:
public class HomeController: Controller
{
public ActionResult Index()
{
// TODO: Fetch an actual domain model from your repository,
// and map it to the view model (AutoMapper is a great tool for the job)
var model = new ParentViewModel
{
Name = "parent name",
Children = Enumerable.Range(1, 5).Select(x => new ChildViewModel
{
Name = "child " + x
})
};
return View(model);
}
[HttpPost]
public ActionResult Index(ParentViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// TODO: the model object here will contain the new values
// => user AutoMapper to map it back to a domain model
// and pass this domain model to the repository for processing
return RedirectToAction("Index");
}
}
そして最後にビュー:
@model ParentViewModel
@using (Html.BeginForm())
{
<h2>Parent</h2>
<div>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
@Html.ValidationMessageFor(x => x.Name)
</div>
<h2>Children</h2>
<table>
<thead>
<tr>
<th>Child name</th>
</tr>
</thead>
<tbody>
@Html.EditorFor(x => x.Children)
</tbody>
</table>
<input type="submit" value="OK" />
}
最後の部分は、子のエディターテンプレートです(~/Views/Home/EditorTemplates/ChildViewModel.cshtml
):
@model ChildViewModel
<tr>
<td>
@Html.LabelFor(x => x.Name)
@Html.EditorFor(x => x.Name)
@Html.ValidationMessageFor(x => x.Name)
</td>
</tr>