0

When I fill in the information on my add product page and try to save, I get the error.

public ActionResult Create()
    {
        List<SelectListItem> values= (from i in db.Categories.ToList()
                                         select new SelectListItem
                                         {
                                             Text = i.Name,
                                             Value = i.Id.ToString()
                                         }
                                         ).ToList();
        ViewBag.val = values;
        return View();
    }

View

<div class="form-group">
    @Html.LabelFor(model => model.CategoryId, "CategoryId", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(m=> m.CategoryId ,(List<SelectListItem>)ViewBag.val, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
    </div>
</div>

Error

System.InvalidOperationException: 'The ViewData item that has the key 'CategoryId' is of type 'System.Int32' but must be of type 'IEnumerable'.'

Progman
  • 16,827
  • 6
  • 33
  • 48
vio
  • 1
  • 1

1 Answers1

0

ViewBag doesn't require type-casting, try changing your code in View from

@Html.DropDownListFor(m=> m.CategoryId ,(List)ViewBag.val, new { @class = "form-control" })

to

@Html.DropDownListFor(m=> m.CategoryId ,@ViewBag.val, new { @class = "form-control" })

Or, you may also refer this SO answer

and use something like below -

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")
Rajeev Pande
  • 456
  • 3
  • 8