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

0

I'm starting a new project and I'm migrating from webForm to MVC and I confess that I miss the best basic questions for some.

Well one of those questions is the following, I need to create a dropDownList and the data of this both the ID and the Name I have in a table in the database. The persistence of the data I work with Entity Framework.

How do I send the data from the model? Can you help me with an example?

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

In this way, from the controller I can fill 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? Besides, is this advisable? Do it from the model?

Thank you very much in advance for your help and time

    
asked by jeissoni22 26.10.2016 в 17:45
source

1 answer

1

Greetings jeissoni22, welcome to the site, some time ago I did a workshop on ASP.net MVC from scratch, I hope you find it useful: link + source code on Github link

There are several ways, I present one of them through 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 is through a Model that you will pass to the list. On 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.
    
answered by 26.10.2016 / 19:49
source