DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'CategoryTypeID'
Asked Answered
R

2

14

I am using MVC. I want to pass the category data I entered from my view and passed to my Post/ Createcontroller, but it's not's letting me pass my categoryTypeID that I have selected from my dropdownlist.

Here is the error:

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

Here is my code:

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>
Rozalie answered 20/4, 2012 at 19:55 Comment(0)
M
28

I faced this error. I was binding an object of the View Model:

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

In the View, I created the ListBox like this:

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

It should be like this in fact:

@Html.ListBoxFor(m => m.Panel, new SelectList(Model.Panel, "Value", "Text"))
Minica answered 24/10, 2013 at 15:19 Comment(0)
B
13

You are defining your SelectList twice, in your controller as well as in your view.

Keep the view clean. Just the following would be enough in your case: @Html.DropDownListFor(model => model.CategoryTypeID, (SelectList)ViewBag.CategoryTypes)

I have to admit that DropDownListFor is quite confusing in the beginning :)

Blanton answered 29/4, 2012 at 8:42 Comment(1)
+1. Indeed, I've defined SelectList twice. Your explanation absolutely solved my issue. Now, why the error message doesn't actually say that? I've got similar error: DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a property with the name 'Id'. The error message is some kind misleading, don't you think?Latrice

© 2022 - 2024 — McMap. All rights reserved.