これはどのように達成できますか?
もちろん、ビューモデルを使用して:
public class CountryViewModel
{
public int CountryId { get; set; }
public string CountryName { get; set; }
}
次に、表示ビューをレンダリングすることになっているコントローラー アクションにこのビュー モデルを入力します。
public ActionResult Display(int id)
{
Country country = ... go and fetch from your db the corresponding country from the id
// Now build a view model:
var model = new CountryViewModel();
model.CountryId = country.Id;
model.CountryName = country.Name;
// and pass the view model to the view for displaying purposes
return View(model);
}
もちろん、ビューはビューモデルに強く型付けされます。
@model CountryViewModel
@Html.DisplayFor(x => x.CountryName)
したがって、ASP.NET MVC でわかるように、常にビュー モデルを操作する必要があります。特定のビューでどのような情報を操作する必要があるかを考え、最初にすべきことはビュー モデルを定義することです。次に、ビュー モデルにデータを入力するのは、ビューを提供しているコントローラー アクションの役割です。このビュー モデルの値がどこから来ているかは問題ではありません。ビュー モデルは、多くのデータ ソースを集約する 1 つのポイントと考えてください。
ビューに関する限り、それらは可能な限り愚かであるべきです。ビューモデルで利用可能なものを操作するだけです。