Good afternoon, how can I populate a dropdown with data from a database using pure Ado.net (code) and without using Entity framework?
I have two tables in my database that relate. First I must register a department and when registering a user, there will be a dropdown that will load the registered departments.
In User Model User Model I have defined the following:
public List<SelectListItem> ListaDepartamento { get; set; }
public int DepartamentoSelecionado { get; set; }
I created a file that calls UserHandler and created a function that queries the departments
public List<DepartamentoModel> DepList()
{
Conexao();
List<DepartamentoModel> listaDepartamento = new List<DepartamentoModel>();
string query = "select * from departamento";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
con.Open();
adapter.Fill(dt);
con.Close();
foreach (DataRow dr in dt.Rows)
{
listaDepartamento.Add(new DepartamentoModel
{
Id = Convert.ToInt32(dr["id"]),
Nome = Convert.ToString(dr["nome"])
});
}
return listaDepartamento;
}
In my controller I call within the get method Register, the listing of departments
[HttpGet]
public ActionResult Cadastrar()
{
UsuarioHandler usuariohandler = new UsuarioHandler();
ModelState.Clear();
return View(usuariohandler.DepList());
}
and my view:
@model projetinho.Models.UsuarioModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>UsuarioModel</h4>
@Html.DropDownListFor(model => model.ListaDepartamento, new SelectList(Model.ListaDepartamento, "Value", "Text"), "Selecione")
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
When running, I get the following error:
O item de modelo inserido no dicionário é do tipo'System.Collections.Generic.List'1[projeto.Models.DepartamentoModel]', mas esse dicionário requer um item do tipo 'projeto.Models.UsuarioModel'.