我有一个Edit窗体,上面有几个DropDownList控件。 我需要根据我在db中的数据绑定DropDownListFor中的选定值。
我的下一步是:
型号:
供应商
public class Supplier{
public int SupplierID { get; set; }
public string CompanyName { get; set; }
}
Delviery
public class Delivery{
public int DeliveryID { get; set; }
public string DeliveryCode { get; set; }
public int SupplierID { get; set; }
public virtual Supplier Supplier { get; set; }
}
ViewModel for Delivery Edit屏幕:
public class DeliveryEditViewModel{
public int DeliveryID { get; set; }
public string SelectedCompanyName { get; set; }
public IEnumerable<SelectListItem> Suppliers { get; set; }
}
查看:
<dd>
@Html.DropDownListFor(x => x.SelectedCompanyName, new SelectList(Model.Suppliers, "Value", "Text"), htmlAttributes: new { @class = "form-control" })
</dd>
控制器:
// GET: Deliveries/Edit
public ActionResult Edit(int? id){
db.Configuration.ProxyCreationEnabled = false;
DeliveryEditViewModel model = db.Deliveries.Include(s => s.Supplier).Include(a => a.Auction).Include(q => q.Quality).Include(t => t.BulbType)
.Where(d => d.DeliveryID == id)
.Select(x => new DeliveryEditViewModel{
DeliveryID = x.DeliveryID,
SelectedCompanyName = x.Supplier.CompanyName
})
.Single();
model.Suppliers = db.Suppliers.Where(s => s.IsActive == true).Select(x => new SelectListItem{
Value = x.SupplierID.ToString(),
Text = x.CompanyName
});
return View(model);
}
问题是我无法根据我在数据库中已有的数据在DropDownListFor中设置选定的值。相反,我总是使用DropDown控件,第一个元素处于活动状态。 我已经从Html.DropdownListFor selected value not being set尝试过solutoin,但我仍然选择了第一个值,而不是真正的值。
研究时间和已经大胆的头发让我停下来寻求帮助。 请帮我弄清楚它是如何可能的。
非常感谢你。
答案 0 :(得分:0)
Suppliers
已经IEnumerable<SelectListItem>
为什么世界上你在视图中使用new SelectList(Model.Suppliers, "Value", "Text")
创建另一个相同的?您需要设置SelectedCompanyName
的值以匹配其中一个选项(即您的Suppliers表中SupplierID
的值之一(但您的代码建议该属性应为int
而不是{ {1}})@StephenMuecke
答案 1 :(得分:-1)
正如我所建议你不要在控制器级别创建SelectListItems。你能做的是:
public class DeliveryEditViewModel
{
public int DeliveryID { get; set; }
public string SelectedCompanyName { get; set; }
public IEnumerable<Supplier> suppliers { get; set; }
}
控制器:
// GET: Deliveries/Edit
public ActionResult Edit(int? id){
db.Configuration.ProxyCreationEnabled = false;
DeliveryEditViewModel model = db.Deliveries.Include(s => s.Supplier).Include(a => a.Auction).Include(q => q.Quality).Include(t => t.BulbType)
.Where(d => d.DeliveryID == id)
.Select(x => new DeliveryEditViewModel{
DeliveryID = x.DeliveryID,
SelectedCompanyName = x.Supplier.CompanyName
})
.Single();
Model.suppliers = db.Suppliers.Where(s => s.IsActive == true);
return View(model);
}
查看:
@Html.DropDownListFor(model => model.SelectedCompanyName, ((IEnumerable<Supplier>)Model.supplierss).Select(x => new SelectListItem()
{
Text = x.CompanyName.ToString(),
Value = x.SupplierID.ToString(),
Selected = (Model != null) && (x.CompanyName == Model.SelectedCompanyName)
}), "-- Select Supplier --")
这是一个非常有用的技巧,您可以更改文本或值或选定值或默认选定选项,而无需更改控制器并再次构建它以反映。