How to fill a Dropdownliste with ASP MVC

Asked

Viewed 681 times

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?

  • 1

    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'.

  • That’s because you declare in your view @model projetinho.Models.UsuarioModel and sends a List<DepartamentoModel> in his Controller in Return View(usuariohandler.DepList());

  • 1

    @Leandroangelo well noted! Thank you so much for your help.!!

1 answer

1

MVC Dropdown methods use lists SelectList with the data. They also support storing the user’s last selection, by the way. So you can either send this SelectList by Viewbag or add a property to your model.

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);
}

Aí na View

@Html.DropdownListFor(model => model.ListaDepartamento, ViewBag.departamentos as SelectList, new { @class = "form-control" })
  • 1

    Thank you so much for your help, tiramonium!! Worked out using Viewbag

  • Tavlez would be better if you create a Viewmodel with the necessary structure for your view

  • 1

    The dropdown is being filled with database values, however I am having the following error when I have saved: System.Invalidoperationexception: 'There is no Viewdata item of type 'Ienumerable<Selectlistitem>' which has the 'List department' key'.'

  • It is because you need to add the Viewbag statement both in the method HttpGet how much in the HttpPost, if the post redirects to the same View.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.