首页 文章

从枚举创建下拉列表并将数据绑定到EF模型属性

提问于
浏览
1

我试图将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.IsValidfalse .
2.对于第二个下拉代码:我得到"The field Location Type must be a number."这是有道理的,因为Location Type是一个整数字段 .

1 回答

  • 0

    这是我最近开发的网站的工作示例 . EnumDropdown 用于循环 .

    //models
    public enum SystemDocType
    {
        [Display(Name = "Other")]
        Unknown,
        [Display(Name = "Condominium Certification")]
        CondominiumCertification,
        [Display(Name = "Previous Fiscal Years Ending Income/Expense")]
        PrevYearsIncomeExpense,
        [Display(Name = "Reserve Study")]
        ReserveStudy
        //more
    }
    public class DocumentType
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "System Doc Type")]
        public SystemDocType? SysDocType { get; set; }
        //more
    }
    
    //controller
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Route("condo/updatedoctype")]
    public async Task<ActionResult> UpdateDocType(FormCollection data, int itemid)
    {
        var docType = context.DocTypes.Where(t => t.Id == itemid).FirstOrDefault();
        if (docType != null)
        {
            string val = data["item:" + itemid.ToString() + ":name"];
            int sysType = int.Parse(data["item:" + itemid.ToString() + ":sysdoctype"]);
            docType.TypeName = val;
            docType.SysDocType = (SystemDocType)sysType;
            await context.SaveChangesAsync();
            return RedirectToAction("DocTypes");
        }
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    
    //.shtml (razor)
    @model IEnumerable<fhaApproved2.Models.DocumentType>
    @* more *@
    @foreach (var item in Model) {
        @Html.EnumDropDownListFor(m => item.SysDocType, 
                htmlAttributes: new { @class = "form-control", @Name = "item:" + @item.Id + ":sysdoctype" })
        <button class="btn btn-primary" type="submit" title="Update Document Type" formaction="/condo/updatedoctype" name="itemid" formmethod="post" value="@item.Id">
            <span class="glyphicon glyphicon-floppy-save"></span>
        </button>
    }
    

相关问题