0
I am trying to create a Select List, but in case it is returning it to my view:
Microsoft.AspNetCore.Mvc.Rendering.Selectlistitem
so 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;
}
}
Let me see if I understand your problem, you’re clicking on the add and you’re not updating the dropdown? Or Dropdown is not creating a selectlist-item?
– Angelo Simonato
Dropdown is not creating a selectlist, it is placing that message according to the image I put in the question.
– Matheus
Matheus, is this using in your controller? using Microsoft.AspNetCore.Mvc.Rendering;
– Angelo Simonato
using Microsoft.AspNetCore.Mvc.Rendering; is in the folder
Services
, where I search the data.– Matheus
Is there a possibility that the return of your select is coming blank? (I can’t open the image because I’m at work)
– Angelo Simonato
Worst I’ve ever done these tests he’s returning the values correctly.
– Matheus
The mistake is in
GetAllOfficeAsync
, it is searching the data correctly, but when it gives the Returnresult
, it overwrites the data.– Matheus