如何使用来自 SQL 数据库 table 的数据在 Razor 中填充 Select taghelper

How to populate a Select taghelper in Razor using data from a SQL database table

我正在使用 ASP.NET Core 1.0 和 EF Core 1.0,并且在我的 SQL 数据库中有以下代码优先 class。

namespace GigHub.Models
{
  public class Genre
  {
    public byte Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }
  }
}

我还有以下 ViewModel class 我在 Razor 视图表单中使用:

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>

我基本上无法理解如何以 Select taghelper [=37= 的形式将我的类型列表从我的数据库中获取到 ViewModel 属性 ]-items= 可以消耗。我经历的许多反复试验通常会导致从通用 List<> 类型到 MVC SelectListItem[=30= 类型的转换问题] 类型。我怀疑我的 ViewModel 类型 class 需要调整,但到目前为止我的研究只产生了涵盖 ASP.NET 和 Entity Framework 以前版本的文章,我很难将它们映射到 ASP.NET 核心1.0 RC2 和 EF 核心 1.0.

您可以使用 asp-for 为 select 元素指定模型 属性 名称,并使用 asp-items 指定选项元素。

<select asp-for="SomeFiles" asp-items="Model.SomeOptions"></select> 

如果您不想将 SomeOptions 字段添加到模式,您也可以使用 ViewBag.SomeOptions

有关详细信息,请查看 The Select Tag Helper 文档。

例子

查看

<select asp-for="Country" asp-items="Model.Countries"></select> 

型号

using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

namespace FormsTagHelper.ViewModels
{
    public class CountryViewModel
    {
        public string Country { get; set; }

        public List<SelectListItem> Countries { get; set; }
    }
}

控制器

Index 方法初始化 CountryViewModel,设置 selected 国家和国家列表,并将模型传递给 Index 视图。

public IActionResult Index()
{
    var model = new CountryViewModel();
    model.Country = "CA";
    model.Countries = db.Countries
                        .Select(x => new SelectListItem { Value = x.Id, Text = x.Name })
                        .ToList();

    return View(model);
}