How to fill a Dropdown List with ASP MVC

0

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'. 
    
asked by anonymous 07.02.2018 / 16:29

1 answer

2

MVC's DropDown methods use SelectList lists with the data. They also support storing the user's last selection, incidentally. Then you can either send this SelectList to ViewBag or add a property to your template.

public SelectList DepList(){
    Conexao();

    List<DepartamentoModel> listaDepartamento = new List<DepartamentoModel>();

    // resto do código aqui

    // Lista/coleção com os dados, valor de cada opção do dropdown,
    // texto de cada opção e opção selecionada da lista
    SelectList dropdownDepartamento = new SelectList(listaDepartamento, "id", "nome", null);

    return dropdownDepartamento;
}

Or by ViewBag.

public ActionResult Cadastrar(){
    UsuarioHandler usuarioHandler = new UsuarioHandler();
    ModelState.Clear();
    ViewBag.departamentos = new SelectList(usuarioHandler.DepList(), "id", "nome", null);
}

There in the View

@Html.DropdownListFor(model => model.ListaDepartamento, ViewBag.departamentos as SelectList, new { @class = "form-control" })
    
07.02.2018 / 16:58