-->

数据绑定:“System.Web.Mvc.SelectListItem”不包含与名称的属性“Cate

2019-06-23 19:42发布

我使用MVC。 我想通过我从我的观点进入,经过我的帖子/ Createcontroller类别的数据,但它不是真实让我通过我的categoryTypeID,我已经从我的下拉列表中选择。

以下是错误:

数据绑定:“System.Web.Mvc.SelectListItem”不包含名为“CategoryTypeID”的属性。

这里是我的代码:

My CreateController:
//
        // POST: /Category/Create

        [HttpPost]
        public ActionResult Create(Category category)
        {
            if (ModelState.IsValid)
            {
                db.Categories.Add(category);
                db.SaveChanges();
                return RedirectToAction("Index");
            }


            ViewBag.CategoryTypes = new SelectList(db.CategoryTypes, "CategoryTypeID", "Name", category.CategoryTypeID);

            return View(category);
        }
My Create View
@model Haykal.Models.Category




<div class="editor-label">
            @Html.LabelFor(model => model.CategoryTypeID, "CategoryType")
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.CategoryTypeID,
            new SelectList(ViewBag.CategoryTypes as System.Collections.IEnumerable, "CategoryTypeID", "Name"),
          "--select Category Type --", new { id = "categoryType" })
            @Html.ValidationMessageFor(model => model.CategoryTypeID)
        </div>

Answer 1:

我遇到这个错误。 我是有约束力的视图模型的对象:

editPanelViewModel.Panel = new SelectList(panels, "PanelId", "PanelName");

在视图中,我创建列表框是这样的:

@Html.ListBoxFor(m => m.Panel, new SelectList(Model.Panel, "PanelId", "PanelName"))

它应该是这样的事实上:

@Html.ListBoxFor(m => m.Panel, new SelectList(Model.Panel, "Value", "Text"))


Answer 2:

您要定义SelectList两次,在你的控制器,以及在您的视图。

保持清洁的观点。 只需以下就足够了,你的情况: @Html.DropDownListFor(model => model.CategoryTypeID, (SelectList)ViewBag.CategoryTypes)

我不得不承认,DropDownListFor在开始时是相当混乱:)



文章来源: DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'CategoryTypeID'