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" })
This error usually occurs when the list is empty (null). If you debug your view Viewbag.Office has information?
– George Wurthmann
ah understood, and if I have no value in Viewbag, would return the blank value or just "Select your option", something like this ?
– Matheus
You can handle it in a few ways, I’ll come up with an answer for you already including the list problem being empty.
– George Wurthmann
Beauty, I await your reply then @Georgewurthmann
– Matheus