Personal I'm trying to create a Select List, but in case it's returning this to my view:
Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
so it is not returning the Cargos
that are in my database
and here are the codes I use.
View:
@if (ViewBag.Office != null)
{
@Html.DropDownList("Office", ViewBag.Office as SelectList, htmlAttributes: new { @class = "form-control" })
<div class="input-group-append" data-toggle="modal" data-target="#cadastra-cargo">
<a class="btn btn-default">Adicionar</a>
</div>
<span asp-validation-for="Office" class="text-danger"></span>
}
else
{
<select class="form-control" asp-for="Office">
<option value="">Adicione um cargo</option>
</select>
<div class="input-group-append" data-toggle="modal" data-target="#cadastra-cargo">
<a class="btn btn-default">Adicionar</a>
</div>
<span asp-validation-for="Office" class="text-danger"></span>
}
Controller:
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Add(string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
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)}'.");
}
ViewBag.Office = _employeeManager.GetAllOfficeAsync(user.Id);
return View();
}
GetAllOfficeAsync Service:
public SelectList GetAllOfficeAsync(Guid user)
{
try
{
var lista = _context.FuncionariosCargo.Where(x => x.UsuarioId == user)
.OrderBy(x => x.Cargo)
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.Cargo
});
SelectList result = new SelectList(lista);
return result;
}
catch (Exception)
{
throw;
}
}