我试图将dropdownlist选择的值绑定到模型属性,并在多次尝试后,我无法弄清楚这里可能有什么问题 .
我想了解如何在表单提交时,用户从下拉列表中选择的值将填写EF模型的属性 . 其中 model.tblPickup.LocationList
是ENUM, model.tblPickup.LocationType
是EF模型属性 .
MVC (razor) code
<div class="form-group">
@Html.LabelFor(model => model.tblPickup.LocationType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EnumDropDownListFor(model => model.tblPickup.LocationList, "Select Address Type", new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.tblPickup.LocationType, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.tblPickup.LocationType, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.tblPickup.LocationType, new SelectList(Enum.GetValues(typeof(WBusiness.Models.LocationTypes))), "Select Address Type", new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.tblPickup.LocationType, "", new { @class = "text-danger" })
</div>
</div>
Code Behind - It's a composite model with three classes:
//Actual class creatd by EF
public partial class tblLocation
{
public int Id { get; set; }
public string LocationName { get; set; }
public string OtherDetails { get; set; }
public Nullable<decimal> Latitude { get; set; }
public Nullable<decimal> Longitude { get; set; }
public string GoogleLink { get; set; }
public string PhoneNumber { get; set; }
public Nullable<int> LocationType { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public Nullable<System.DateTime> UpdateDate { get; set; }
public Nullable<int> ProfileId { get; set; }
public Nullable<bool> Deleted { get; set; }
public Nullable<System.DateTime> DeleteDate { get; set; }
public virtual tblProfile tblProfile { get; set; }
}
//Partial class to add custom property
public partial class tblLocation
{
public LocationTypes LocationList { get; set; }
}
//ENUM class
public enum LocationTypes
{
Pickup = 1,
Delivery = 2
}
//Composit class with order and location in it
public class OrderDetailModel
{
public tblOrder tblOrder { get; set; }
public tblLocation tblPickup { get; set; }
}
//Controller code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OrderDetailModel model)
{
if (ModelState.IsValid)
{
db.tblOrders.Add(model.tblOrder);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
当我尝试提交表单时 . 我收到以下错误:
1.对于第一个下拉列表:虽然该字段是整数类型,但我到达后面的代码,但是 ModelState.IsValid 是 false .
2.对于第二个下拉代码:我得到"The field Location Type must be a number."这是有道理的,因为Location Type是一个整数字段 .
1 回答
这是我最近开发的网站的工作示例 .
EnumDropdown
用于循环 .