【发布时间】:2016-12-01 22:52:22
【问题描述】:
我正在使用 ASP.NET Core 1.0 和 EF Core 1.0,并且在我的 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 代码以访问 Genre 属性。
<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>
我基本上无法理解如何以 Select taghelper asp-items= 可以使用的形式将我的类型列表从我的数据库中获取到 ViewModel 属性中。我经历的许多反复试验通常会导致从通用 List 类型到 MVC SelectListItem 类型的转换问题。我怀疑我的 ViewModel Genre 类需要调整,但到目前为止我的研究只产生了涵盖以前版本的 ASP.NET 和 Entity Framework 的文章,我很难将它们映射到 ASP.NET core 1.0 RC2 和 EF Core 1.0。
【问题讨论】:
-
<select asp-for="FieldName" asp-items="ViewBag.OptionsCollection"></select> -
有没有办法避免 ViewBag 并按照 asp-items="Model.MyGenreListHere" 的行将 ViewModel 中的列表转换为 taghelper 的列表形式?这是我要出错的地方吗?
-
只需在 ViewModel 中使用一个字段。我将发布一个来自 ASP.NET 文档的示例。
-
我怀疑我的根本问题是从我的 ViewModel 属性中的 List
到类似 IEnumerable 的东西,但语法使我无法理解。关于 C#,我还有很多东西要学。
标签: c# razor asp.net-core-1.0 tag-helpers