「Database First Model」を使用して ASP.NET Core MVC RC2 プロジェクトを使用しています。データベースは有名な Northwind データベースです。データが空でなくViewBag
ても、データがViewBag
入力されるはずの「タグ ヘルパーの選択」(HTML ドロップダウン リスト) が空であることを除いて、すべて正常に動作します。
次のアクション メソッドは、CustomersController
すべての顧客のリストを正しく表示します。
public IActionResult Index()
{
List<Customers> data = repository.SelectAll();
return View("/views/Northwind/Index.cshtml", data);
}
ユーザーがレコードの [編集] リンクをクリックすると、次のアクションにより、国のドロップダウンが空であることを除いて、Edit
そのレコードの値が編集フォームに正しく表示されます。
public IActionResult Edit(string id)
{
Customers data = repository.SelectByID(id);
var query = (from c in repository.Context.Customers
orderby c.Country ascending
select new SelectListItem() { Text = c.Country, Value = c.Country }
).Distinct();
List<SelectListItem> countries = query.ToList();
ViewBag.Countries = countries;
return View("/views/Northwind/Edit.cshtml", data);
}
以下は、ドロップダウンが空白であることを除いて、編集可能なデータを表示する「ビュー」です。
@model MVCCoreCR2_Project.Models.Customers
<div class="form-group">
<label asp-for="Country" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Country" asp-items="@ViewBag.Countries" class="form-control" />
<span asp-validation-for="Country" class="text-danger" />
</div>
</div>
注: デバッグ中にブレークポイントを置いて<select asp-for="Country" asp-items="@ViewBag.Countries" class="form-control" />
カーソル@ViewBag.Countries
を合わせると、ViewBag 内の国が入力されていることがわかります。