我正在使用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文档中发布一个示例。 –