Asp.net
在 ASP.net Core 中填充下拉列表
有誰知道如何處理 Asp.net 核心中的下拉菜單。我想我讓自己很難理解新的 Asp.net 核心概念。(我是 Asp.net Core 的新手)。
我有模型稱為
Driver,Vehicle。基本上,一個人可以在 master 中創建一堆車輛,然後將其附加到 Driver。這樣駕駛員就會與車輛相關聯。我的問題是我也在某些區域使用 viewmodel 來組合兩個不同的模型。(從預設模板中了解很少)
我的問題是我不知道下一步是什麼,因為 ASP.net Core 是最新的,沒有很多教程和 Q/As 可用。
驅動器型號
public class Driver { [Required] public int Id { get; set; } [Required] public string ApplicationUserId { get; set; } [Required] public int VehicleId { get; set; } [Required] public string Status { get; set; } public virtual ApplicationUser ApplicationUser { get; set; } public virtual Vehicle Vehicle { get; set; } }車型
public class Vehicle { [Required] public int Id { get; set; } [Required] public string Make { get; set; } public string Model { get; set; } [Required] public string PlateNo { get; set; } public string InsuranceNo { get; set; } }驅動視圖模型
public class DriverViewModel { [Required] [Display(Name = "ID")] public int ID { get; set; } [Required] [Display(Name = "User ID")] public string ApplicationUserId { get; set; } [Required] [Display(Name = "Vehicle ID")] public IEnumerable<Vehicle> VehicleId { get; set; } //public string VehicleId { get; set; } [Required] [Display(Name = "Status")] public string Status { get; set; } }這是我的看法
<div class="col-md-10"> @*<input asp-for="VehicleId" class="form-control" />*@ @Html.DropDownList("VehicleId", null, htmlAttributes: new { @class = "form-control"}) <span asp-validation-for="VehicleId" class="text-danger" /> </div>
查看文件,似乎 asp.net 核心可能正在遠離 HTML 幫助器並轉向使用標記幫助器。以下連結應該有所幫助
<https://docs.asp.net/en/latest/mvc/views/working-with-forms.html#the-select-tag-helper>
具體來說
@model CountryViewModel <form asp-controller="Home" asp-action="Index" method="post"> <select asp-for="Country" asp-items="Model.Countries"></select> <br /><button type="submit">Register</button> </form>請注意“asp-for”的使用,它引用了要綁定的模型屬性,以及“asp-items”的使用,它引用了選擇列表項列表的模型屬性源,以及它如何應用於選擇標籤
為了完整起見,下面引用了文件中使用的範例模型
namespace FormsTagHelper.ViewModels { public class CountryViewModel { public string Country { get; set; } public List<SelectListItem> Countries { get; } = new List<SelectListItem> { new SelectListItem { Value = "MX", Text = "Mexico" }, new SelectListItem { Value = "CA", Text = "Canada" }, new SelectListItem { Value = "US", Text = "USA" }, }; } }