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

Viewed 39

when i run the code it gives InvalidOperationException: The ViewData item that has the key 'Id' is of type 'System.Int32' but must be of type 'IEnumerable'. error what should i do

    //Controller
    public IActionResult Create()
    {   
        //ViewBag.Dersler = new SelectList(_db.Dersler.ToList(), "PKfromDersler", "DersName");
        List<SelectListItem>values=(from Ders in _db.Dersler.ToList()
            select new SelectListItem
            {
                Text=Ders.DersName,
                Value=Ders.Id.ToString()
            }).ToList();
        ViewBag.v1 = values;

        
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Ogretmen obj)
    {
        if (ModelState.IsValid)
        {
            _db.Ogretmenler.Add(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(obj);
    } 





    //view
    <div class="mb-3">
        <h6 >Ders Seçiniz</h6>
        @Html.DropDownListFor(Ders=>Ders.Id,(IEnumerable<SelectListItem>)ViewBag.v1)
    </div>
2 Answers

You may try

@Html.DropDownListFor(Ders=>Ders.Id,new SelectList(ViewBag.v1,"Value","Text"))

This is my test result.

    public IActionResult Index()
    {
        var value = new List<UserModel>
        {
            new UserModel{ id = 1, name = "user1" },
            new UserModel{ id = 3, name = "user3" }
        };
        ViewBag.v1 = value;
        return View();
    }

enter image description here

As I noticed you didn't pass the model to View

Bellow are the following steps

  1. First get all the list from Dersler table
  2. Initialize ViewBag by creating selectlist and pass the list you generate in first step.
  3. Pass model to view.
  4. Use Html.DropDownListFor to create dropdown using ViewBag as selectlist
public IActionResult Create()
{   
    //ViewBag.Dersler = new SelectList(_db.Dersler.ToList(), "PKfromDersler", "DersName");
    
    var values = (from Ders in _db.Dersler
                  select Ders).ToList();
    ViewBag.v1 = new SelectList(values, "Id", "DersName");
    return View(new Ogretmen()); //Here pass the model object
}

View

@model Ogretmen

<!--
    Your view code...
    ...
    @*
        model.yourId is the id of Ogretmen class for which you bind the value from dropdownlist
    *@
    @Html.DropDownListFor(model => model.yourId, (IEnumerable<SelectListItem>)ViewBag.v1, "-- Option label --", new { @class = "form-control" })
    ...
-->
Related