Create Dropdownlist with Viewbag

Asked

Viewed 645 times

1

I’m getting the following error:

Invalidoperationexception: There is no Viewdata item of type 'Ienumerable' that has the key 'Office'.

Here I search from 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 View, where I try to create the field:

 @Html.DropDownList("Office", ViewBag.Office as SelectList, htmlAttributes: new { @class = "form-control" })
  • 1

    This error usually occurs when the list is empty (null). If you debug your view Viewbag.Office has information?

  • ah understood, and if I have no value in Viewbag, would return the blank value or just "Select your option", something like this ?

  • You can handle it in a few ways, I’ll come up with an answer for you already including the list problem being empty.

  • Beauty, I await your reply then @Georgewurthmann

1 answer

2


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

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

1- Example to put 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 is not null in the View:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.