Create DropDownList with ViewBag

1

I'm getting the following error:

  

InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the 'Office' key.

Here I look for the database:

public IEnumerable<SelectListItem> GetAllOfficeAsync(Guid user)
{
    try
    {
        IEnumerable<SelectListItem> result =  _context.FuncionariosCargo.Where(x => x.UsuarioId == user)
                                                      .OrderBy(x => x.Cargo)
                                                      .Select(c => new SelectListItem
                                                      {
                                                          Value = c.Id.ToString(),
                                                          Text = c.Cargo
                                                       });


         return result;
    }
    catch (Exception)
    {
        throw;
    }
}

Here I create ViewBag:

[HttpGet]
public async Task<IActionResult> Index()
{
    var user = await _userManager.GetUserAsync(User);

    if (user == null)
    {
        throw new ApplicationException($"Não é possível carregar o usuário com o ID '{_userManager.GetUserId(User)}'.");
    }

    var model = await _employeeManager.SearchEmployee(search.ToString(), page, user.Id);

    ViewBag.Office = _employeeManager.GetAllOfficeAsync(user.Id);

    return View(model);
}

And finally to View, where do I try to create the field:

 @Html.DropDownList("Office", ViewBag.Office as SelectList, htmlAttributes: new { @class = "form-control" })
    
asked by anonymous 01.11.2018 / 14:43

1 answer

0

The error may be occurring because your ViewBag.Office is empty (null).

To avoid the problem you can treat the field in some ways.

1- Example for a generic value in the list in the controller:

if(((SelectList)ViewBag.Office) == null)
{
    ViewBag.Office = new SelectList(new[] {
         new SelectListItem  { Value="0", Text="Valores não encontrados" }
    }, "Value", "Text");
}

2 Example to only show the field if it was not null in the View:

@if (ViewBag.Office != null)
{
    @Html.DropDownList("Office", ViewBag.Office as SelectList, new { @class = "form-control" })
}
    
01.11.2018 / 17:55