2016-09-16 188 views
0

有誰知道如何處理Asp.net核心中的Dropdowns。我想我讓自己很難理解新的Asp.net核心概念。 (我是Asp.net核心新手)。在ASP.net Core中填充下拉列表

我有模型叫Driver,Vehicle。基本上可以在主人中創建一堆車輛,然後將其附加到司機。這樣駕駛員將與車輛相關聯。

我的問題是,我也使用視圖模型在某些區域,以兩種不同的模式結合起來。(瞭解從默認模板小)

我的問題是我不知道是因爲ASP.net核心下一步是最新的,沒有很多教程和Q/A可用。

驅動程序模型

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 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; } 


} 

這裏的

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; } 

} 

視圖模型是我的看法

<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> 

回答

5

看看文檔,看起來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-的」它引用的模型屬性綁定和使用「ASP-項目」,它引用選擇列表項目清單的模型屬性源以及如何將其應用於選擇標記

以下爲了完整性參考文檔中使用的示例模型

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" }, 
    }; 
} 
} 
+0

感謝您的時間,我剛剛從一分鐘前來源於同一個源:) – Kirk