as I create dropDownList with Entity Framework in Asp.net MVC

I am starting a new project and I am migrating from webForm to MVC and I confess that I skip basic doubts at best for some.

Well one of those questions is as follows, I need to create a dropDownList and the data from this both the ID and the name I have in a table in database. Data persistence I work with Entity Framework.

How do I send the data from the model? could you help me with a example ?

For now I have done it from the controller and I have the following code

This way, from the controller I can populate the dropdownlist

// controlador 
    public ActionResult Index()
            {

                using (var contextoBd = new SGDCONSULTA_Entidades())
                {
                    var usuarios = (from sd in contextoBd.t_SoportesDocumentales
                                    select new
                                    {
                                        sd.Id,
                                        sd.NombreSoporte
                                    }).ToList();

                    usuarios.Add(new { Id = 0, NombreSoporte = "-- Seleccione -- " });

                    var listaUsuarios = new SelectList(usuarios.OrderBy(o => o.Id), "Id", "NombreSoporte");

                    ViewData["usuarios"] = listaUsuarios;
                }
                return View();
            }

And from the view I do the following

@Html.DropDownList("usuarios", ViewData["usuarios"] as SelectList, new { @id = "dlUsuarios", @class = "form-control" })

But now if I wanted to do this but from the model how could I do it? in addition, is this advisable? do it from the model ?

Thank you very much for your help and Time

 0
Author: jeissoni22, 2016-10-26

1 answers

Greetings jeissoni22, welcome to the site, a while ago I did a workshop on ASP.net MVC from scratch, I hope will be useful: https://www.youtube.com/watch?v=6LZG76aLykY + source code on Github, https://github.com/fredyfx/UPAOnetStackOverflowES-ASPnetMVC

There are several ways, I present one of them using a ViewBag from the controller where you create a list:

List<Estudiante> lEstudiantes = new List<Estudiante>();
lEstudiantes = db.Estudiantes.ToList();
ViewBag.listaEstudiantes = lEstudiantes;

And in your view:

@Html.DropDownList("Estudiante", new SelectList(ViewBag.listaEstudiantes, "ID", "Nombres"))

Another Way Way is by using a model that you'll be on the list. In your controller:

var modelo = new cEstudianteViewModel();
modelo.listaEstudiantes = ObtenerListaEstudiantes();

And in your view:

@Html.DropDownList("Estudiante", new SelectList(Modelo.listaEstudiantes, "ID", "Nombres")) 
//"ID"-> Key, "Nombres" -> Value.
 2
Author: fredyfx, 2016-10-26 17:49:52