There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'SessionSelect'

30 Views Asked by At

enter image description here

I get the above issue when trying to implement a Dropdown list having Sessions from session activities table. Method in Controller

private void getSessions()
{
    try
    {
        ViewData["Sessions"] = new SelectList(_dbContext.Set<SessionActivity>().Select((x) => new { x.Name, x.SessionDatum.Id }).ToList(), "Id", "Name");
    }
    catch (Exception ex)
    {
        _logger.Error(ex.Message, ex);
    }
}

Coding's used in View

@{
    var sessionSelect = (IEnumerable<SelectListItem>)ViewData["Sessions"];
}
@Html.DropDownList("SessionSelect",sessionSelect, "Please select..", new { @class = "form-control", @id = "SessionSelect" })
1

There are 1 best solutions below

0
Serge On

try to use SelectListItem

 ViewBag.Sessions = _dbContext.Set<SessionActivity>().Select((x) => new SelectListItem {  Text = x.Name, Value= x.SessionDatum.Id.ToSTring }).ToList();

....

 @Html.DropDownListFor(model => model.SessionSelect, ViewBag.Sessions, "select session", new { @class = "form-control" })