在 db 中插入下拉列表列表值

本文关键字:列表 下拉列表 插入 db | 更新日期: 2023-09-27 18:33:16

我在数据库中插入下拉列表的选定值,但它在查看下拉列表助手的位置时给我错误。没有类型为"IEnumerable"的 ViewData 项具有键"SpaceType"。型:

        public class AddSpace
        {
             public string SpaceType { get; set; }
        }

视图:

        @Html.DropDownListFor(m => m.SpaceType,  (IEnumerable<SelectListItem>)ViewData["property"])

控制器

    [HttpGet]
    public ActionResult AddSpace()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        items.Add(new SelectListItem { Text = "Private Residence", Value = "Private Residence" });
        items.Add(new SelectListItem { Text = "Office", Value = "Office" });
        items.Add(new SelectListItem { Text = "Place of worship", Value = "Place of worship" });
        items.Add(new SelectListItem { Text = "Commercial Parking lot", Value = "Commercial Parking lot" });
        items.Add(new SelectListItem { Text = "Retail", Value = "Retail" });
        items.Add(new SelectListItem { Text = "Academic Institution", Value = "Academic Institution" });
        items.Add(new SelectListItem { Text = "Other", Value = "Other" });
        ViewData["property"] = items;

}

     [HttpPost]
     public ActionResult AddSpace(AddSpace adspace)
    {
        if (ModelState.IsValid)
        {
            string userName = "wasfa_anjum@yahoo.com";
            var query = from q in Session.Query<Registration>()
                        where q.Email == userName
                        select q;
            Session.Store(adspace);
                Session.SaveChanges();

        }
        else ModelState.AddModelError("","Please Correct the errors to continue");
        return View();
    }

在 db 中插入下拉列表列表值

投射到列表:

  @Html.DropDownListFor(m => m.SpaceType, (List<SelectListItem>)ViewData["property"])

你试过吗[更新]:

@Html.DropDownList("SpaceTypes", ViewData["property"] as SelectList)

另外,在:

items.Add(new SelectListItem { Text = "Other", Value = "Other" });

您可能需要添加:

items.Add(new SelectListItem { Text = "Other", Value = "Other" }, "Text", "Value", 1);

[已添加]或者,您也应该能够像这样编写它:

var items = new SelectList(new[]
    new { Text = "Private Residence", Value = "Private Residence" },
    new { Text = "Office", Value = "Office" },
    new { Text = "Place of worship", Value = "Place of worship" },
    new { Text = "Commercial Parking lot", Value = "Commercial Parking lot" },
    new { Text = "Retail", Value = "Retail" },
    new { Text = "Academic Institution", Value = "Academic Institution" },
    new { Text = "Other", Value = "Other" },
"Text", "Value", 1);
ViewData["property"] = items;