我正在使用ASP.NET Core 1.0和EF Core 1.0,並在我的SQL數據庫中具有以下代碼優先類。如何使用SQL數據庫表中的數據填充剃刀中的選擇標籤幫助
namespace GigHub.Models
{
public class Genre
{
public byte Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
}
}
我也有我的Razor視圖的形式使用下面的ViewModel類:
namespace GigHub.ViewModels
{
public class GigFormViewModel
{
public string Venue { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public List<Genre> Genres { get; set; }
}
}
我也有此控制器:
using GigHub.Data;
using GigHub.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace GigHub.Controllers
{
public class GigsController : Controller
{
private readonly ApplicationDbContext _context;
public GigsController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Create()
{
var vm = new GigFormViewModel();
// Need to get my Genre list from the DbSet<Genre> in my database context injected above
// into the GigFormViewModel for the Select taghelper to consume
return View(vm);
}
}
}
我有我的Razor視圖設置成使用ViewModel的罰款,但我不確定如何設置下面的Select taghelper代碼來訪問流派屬性。
<div class="form-group">
<label asp-for="????" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="????" asp-items="????" class="form-control"></select>
<span asp-validation-for="????" class="text-danger" />
</div>
</div>
基本上,我有麻煩所著的Grokking如何從我的數據庫中獲取我的流派列表插入到視圖模型財產的形式,選擇taghelper ASP項=可以消耗。我經歷的許多試用&錯誤曲解通常會導致轉換問題從通用列表<>類型到MVC SelectListItem類型。我懷疑我的ViewModel Genre類需要調整,但迄今爲止,我的研究僅導致了涉及ASP.NET和Entity Framework早期版本的文章,並且我努力將它們映射到ASP.NET Core 1.0 RC2和EF Core 1.0。
'<選擇ASP換=「字段名」 ASP項=「ViewBag.OptionsCollection」>' –
有沒有辦法避免ViewBag並沿着從視圖模型獲取列表進入列表的形式爲taghelper asp-items的行=「Model.MyGenreListHere」? 這是我錯了嗎? –
只需在您的ViewModel中使用一個字段。我將從ASP.NET文檔中發佈一個示例。 –