【发布时间】:2016-11-22 04:16:02
【问题描述】:
大家好。 我有下一个问题。
我有编辑表单,上面有几个 DropDownList 控件。 我需要根据数据库中的数据绑定 DropDownListFor 中的选定值。
接下来是我的:
型号:
供应商
public class Supplier{
public int SupplierID { get; set; }
public string CompanyName { get; set; }
}
德尔维耶
public class Delivery{
public int DeliveryID { get; set; }
public string DeliveryCode { get; set; }
public int SupplierID { get; set; }
public virtual Supplier Supplier { get; set; }
}
交付编辑屏幕的视图模型:
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,但我仍然选择了第一个值而不是真正的值。
数小时的研究和已经大胆的头发让我停下来寻求帮助。 请帮我弄清楚这怎么可能。
非常感谢。
【问题讨论】:
-
Suppliers已经是IEnumerable<SelectListItem>为什么要在视图中使用new SelectList(Model.Suppliers, "Value", "Text")创建另一个相同的对象?您需要设置SelectedCompanyName的值以匹配其中一个选项(即SupplierID在Suppliers表中的值之一(但您的代码建议该属性应该是int而不是string) -
@StephenMuecke,非常感谢。我不知道我怎么能错过这个。现在它完美地工作了。你救了我)
标签: c# asp.net .net asp.net-mvc