有谁知道如何处理Asp.net核心中的Dropdown。我想我理解新的Asp.net核心概念让自己变得非常复杂。 (我是Asp.net Core的新手。)
我有名为Driver
,Vehicle
的模型。基本上,人们可以在主人中创建一堆车辆,然后将其附加到驾驶员。这样驾驶员就会与车辆相关联。
我的问题是我也在某些区域使用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; }
}
驱动程序的ViewModel
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>
答案 0 :(得分:16)
看一下文档,似乎asp.net核心可能正在从HTML帮助程序转向使用标记帮助程序。以下链接应该有帮助
具体而言
@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>
注意使用引用Model属性的“asp-for”来绑定和使用“asp-items”,它引用了Select List项列表的模型属性源以及它如何应用于select标签
下面引用文档中使用的示例模型以获得完整性
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" },
};
}
}
答案 1 :(得分:1)
@model EmployeeViewModel
<form asp-controller="Home" asp-action="SaveEmployee">
<label asp-for="DesirablePosition">Desirable Position</label>
<select asp-for="DesirablePosition" asp-items="Model.DesirablePositionItems"></select>
</form>
公共类 EmployeeViewModel {
public string DesirablePosition { get; set; }
public List<SelectListItem> DesirablePositionItems { get; } = new List<SelectListItem> {
new SelectListItem { Value = "j", Text = "Junior" },
new SelectListItem { Value = "m", Text = "Middle" },
new SelectListItem { Value = "s", Text = "Senior" },
};
}
公共类 HomeController : 控制器 {
public IActionResult SaveEmployee(){
return View(new EmployeeViewModel());
}
}