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