我有三个asp mvc模型
单元 [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UnitId {get;组; } [需要] [StringLength(25)] public string UnitName {get;组; } 的银行
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int BankId { get; set; }
[Required]
[StringLength(25)]
public string BankName { get; set; }
的BankAccount
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int BankAccountId { get; set; }
[Required]
public int BankId { get; set; }
[Required]
public int UnitId { get; set; }
[Required]
[StringLength(25)]
public string BankAccountNumber { get; set; }
public virtual Bank Bank { get; set; }
public virtual Unit Unit { get; set; }
BankAccountsController
// GET: BankAccounts/Create
public IActionResult Create()
{
ViewData["BankId"] = new SelectList(_context.Bank, "BankId", "Bank");
ViewData["UnitId"] = new SelectList(_context.Unit, "UnitId", "Unit");
return View();
}
**在创建视图VS 2015脚手架代码**
<div class="form-group">
<label asp-for="UnitId" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="UnitId" class="form-control"></select>
</div>
</div>
<div class="form-group">
<label asp-for="BankId" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="BankId" class ="form-control"></select>
</div>
</div>
下拉列表为空如何解决?
答案 0 :(得分:1)
我认为问题在于缺少ViewData和选择列表之间的关联。
可以看到here,我认为您需要使用asp-items
将ViewData
与select
列表绑定。
<select asp-for="UnitId" class="form-control" asp-items="HereGoesViewDataOrViewBagForUnits"></select>
答案 1 :(得分:0)
控制器新代码
//ViewData["BankId"] = new SelectList(_context.Bank, "BankId", "Bank");
//ViewData["UnitId"] = new SelectList(_context.Unit, "UnitId", "Unit");
ViewData["BankId"] = new SelectList(_context.Set<Bank>(), "BankId", "BankName");
ViewData["UnitId"] = new SelectList(_context.Set<Unit>(), "UnitId", "UnitName");
新视图代码
<select class="form-control"
asp-for="UnitId"
asp-items="ViewBag.UnitId"></select>
<select class ="form-control"
asp-for="BankId"
asp-items="ViewBag.BankId"></select>