I am starting a new project and I am migrating from webForm to MVC and I confess that I have doubts that may be basic 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. I work with the persistence of the data with the Entity Framework.
How do I send the data from the model? Could you help me with an 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? Also, is this recommended? do it from the model?
Thank you very much in advance for your help and time.
Greetings jeissoni22, welcome to the site, a while ago I did a workshop on ASP.net MVC from scratch, I hope you find it useful: https://www.youtube.com/watch?v=6LZG76aLykY + source code on Github https:/ /github.com/fredyfx/UPAOnetStackOverflowEN-ASPnetMVC
There are several ways, I present one of them through a ViewBag from the controller where you create a list:
And in your view:
Another way is through a Model that you will pass to the list. In your controller:
and in your view: