0
Good afternoon, as I can fill a dropdown with data from a database using pure Ado.net (code) and without using Entity framework?
I have two tables in my bank 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 set 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 inside 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 executing I got 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'.
What is the specific error or problem?
– Leandro Angelo
My biggest question is how to fill a dropdown. I followed a listing template that I have but didn’t work. It displays the error: The model item inserted in the dictionary is of the type'System.Collections.Generic.List`1[project.Models.Departamentomodel]', but this dictionary requires an item of the type 'project.Models.Usuariomodel'.
– Leonardo
That’s because you declare in your view
@model projetinho.Models.UsuarioModel
and sends aList<DepartamentoModel>
in hisController
in ReturnView(usuariohandler.DepList());
– Leandro Angelo
@Leandroangelo well noted! Thank you so much for your help.!!
– Leonardo