I do it in the following way, I do not know if it is useful for you but here I am sending it to you, these are examples:
COUNTRIES
IEnumerable<Pais> paises()
{
List<Pais> temporal = new List<Pais>();
SqlCommand cmd = new SqlCommand("Select Idpais, NombrePais from tb_paises", con);
con.Open();
SqlDataReader rea = cmd.ExecuteReader();
while (rea.Read())
{
Pais p = new Pais();
p.Idpais = rea.GetString(0);
p.NombrePais = rea.GetString(1);
temporal.Add(p);
}
rea.Close();
con.Close();
return temporal;
}
ADD [GET]
public ActionResult Agregar() //Esta es la presentación de la pagina
{
//Envío a la pagina la lista de los paises
ViewBag.paises = new SelectList(paises(), "idpais", "nombrepais");
//Enviar a la pagina un nuevo Cliente
return View(new Cliente());
}
ADD [POST]
[HttpPost]
public ActionResult Agregar(Cliente c)
{
......................
ViewBag.paises = new SelectList(paises(), "idpais", "nombrepais", c.idpais); //El 4to parametro sirve que se quede seleccionado el ultimo valor que escogí del DropDown al momento de realizar otro "Create"
return View(c);
}
VIEW OF ADDING
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(model => model.idpais, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("idpais", (SelectList)ViewBag.paises)
</div>
</div>
}
You're probably a bit confused but I'll explain, what I do is create a separate method and then call it and fill in the data. The ActionResult "Add" what it does is an insert, but that does not interest us, what matters is the code that is below, in the GET method you see that I am putting a viewBag countries, this viewBag I am sending it to the view with the value "new SelectList (countries ()," idpais "," nombrepais ");", which is a list where the first parameter would be the method that we created, then the second would be the values that are to be sent and the third the values that are going to be shown. When you run it all will be fine, but when you want to send values to the database in the case of a register, we use the POST, in the ActionView Add [POST] what we do is put the same and with a fourth parameter that would be the value that was selected in the GET, remember that in the GET only shows in the "view" and in the POST the data is sent to the database, it would be 2 different views, that is why we put the same. And finally we put the view "@ Html.DropDownList (" idpais ", (SelectList) ViewBag.paises)", this code would be the dropdown and the first parameter would be the id of the selectList that was in the GET and POST, the second parameter would be the ViewBag that we are seeing, also remember that the ViewBag are used to pass data from the controller to the view. And that would be it, if you have questions DO NOT HESITATE TO CONSULT ME. :)