En esta ocación revisaremos el uso de los helpers más complejos (lo que no significa que sea díficil de entender).
@Html.DropDownList / @Html.DropDownListFor
Estos helpers no ayudan a generar las etiquetas <select> y <option>. A partir de una lista podemos crear el combo, a diferencia de otros lenguajes en los que debemos hacer un bucle y crearlos uno por uno.
Antes de empezar agregaremos las siguientes clases, las cuales nos servirán para los ejemplos futuros
using System;
using System.Collections.Generic;
namespace Helpers.Models
{
public class LibroModel
{
public int id { get; set; }
public string Nombre { get; set; }
public AutorModel Autor { get; set; }
public GeneroModel Genero { get; set; }
public string Editorial { get; set; }
public int Edicion { get; set; }
public int Anio { get; set; }
public LibroModel() { }
public LibroModel(int id, string Nombre, int idAutor, int idGenero) {
this.id = id;
this.Nombre = Nombre;
this.Autor = new AutorModel();
this.Autor.id = idAutor;
this.Genero = new GeneroModel();
this.Genero.id = idGenero;
}
}
}
using System;
using System.Collections.Generic;
namespace Helpers.Models
{
public class GeneroModel
{
public int id { get; set; }
public string Nombre { get; set; }
public GeneroModel() { }
public GeneroModel(int id, string Nombre) {
this.id = id;
this.Nombre = Nombre;
}
}
}
Asi mismo agregaremos el siguiente ViewModel
using System;
using System.Collections.Generic;
namespace Helpers.Models
{
public class DetalleLibroViewModel
{
public LibroModel Libro { get; set; }
public List<GeneroModel> ListaGenero { get; set; }
}
}
Dentro de nuestro controlador Home, accion DropDowList agregamos el siguiente código
public ActionResult DropDownList() {
DetalleLibroViewModel model = new DetalleLibroViewModel();
model.Libro = new LibroModel(2,"Paco Yunque",4 ,5);
List<GeneroModel> listaGeneros = new List<GeneroModel>();
listaGeneros.Add(new GeneroModel(1, "Novela"));
listaGeneros.Add(new GeneroModel(2, "Cuento"));
listaGeneros.Add(new GeneroModel(3, "Poema"));
listaGeneros.Add(new GeneroModel(4, "Romance"));
listaGeneros.Add(new GeneroModel(5, "Comedia"));
listaGeneros.Add(new GeneroModel(6, "Drama"));
model.ListaGenero = listaGeneros;
return View(model);
}
Debemos agregar el siguiente codigo dentro de nuestra vista DropDownList:
@model Helpers.Models.DetalleLibroViewModel
@{
ViewBag.Title = "DropDownList";
}
<h2>DropDownList</h2>
Lo normal en lenguajes como asp o php sería recorrer el array o lista con un bucle y generar nuestro combo, lo cual es válido tambien en razor, como veremos a continuación:
<select>
@foreach (Helpers.Models.GeneroModel genero in Model.ListaGenero) {
<option value="@genero.id">@genero.Nombre</option>
}
</select>
<br /><br /><br /><br /><br /><br />
El resultado del código anterior sería
Como vemos el combo se creo sin problemas, revisemos el codigo HTML generado:
<select>
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option value="5">Comedia</option>
<option value="6">Drama</option>
</select>
Ahora mostraremos el uso del helper, para ello listaremos sus principales constructores:
@Html.DropDownList(name)
@Html.DropDownList(name, optionLabel)
@Html.DropDownList(name, selectList)
@Html.DropDownList(name, selectList, htmlAttributes)
@Html.DropDownList(name, selectList, optionLabel)
@Html.DropDownList(name, selectList, optionLabel, htmlAttributes)
@Html.DropDownListFor(m => m.atributo, selectList)
@Html.DropDownListFor(m => m.atributo, selectList, htmlAttributes)
@Html.DropDownListFor(m => m.atributo, selectList, optionLabel)
@Html.DropDownListFor(m => m.atributo, selectList, optionLabel, htmlAttributes)
| Atributo | Tipo Dato | Descripción |
| name | String | Valor que se le dará al atributo name. Si no se especifica el valor del atributo id tendrá el mismo valor name |
| optionLabel | String | Texto por defecto para el combo, solo se indica el texto y su valor sera "" (vacio). Pj: "- Seleccione -" |
| selectList | IEnumerable | Valores que se le asignarán a los tag <option></option>. Este objeto tiene distintas formas de uso las cuales se mostrarán en los ejemplos. En los casos que no se use este objeto explicitamente, deberá existir un ViewData (o ViewBag) con el objeto SelectList. |
| htmlAttributes | Object | Atributos HTML que se deseen agregar a la etiqueta, tales como class, id, style, etc. |
| m => m.atributo | Object | Predicado que indica el el valor de los atributos name y value (tambien el de id si no se especifica). La variable m (puede utilizarse cualquier nombre) representa a la clase especificada en el modelo. Según la propiedad del modelo que utilicemos el atributo name tendrá como valor e. |
Antes de ejecutar el ejemplo debemos agregar el siguiente código a nuestra acción DropDownList (antes de return).
ViewData["Combo1"] = new SelectList(listaGeneros, "id", "Nombre");
ViewData["Combo2"] = new SelectList(listaGeneros, "id", "Nombre");
Ahora agregaremos los siguientes ejemplos de como usar este helper, como ya se habia mencionado son muchas formas en las que se puede utilizar este helper, trataremos de mostrar todas la formas posible y se coloca un comentario sobre cada uno de ellos para su mejor entendimiento
<br /><br />
@*Helper simple sus valores se cargan desde el controlador*@
@Html.DropDownList("Combo1")
@*Helper simple con etiqueta por defecto, sus valores se cargan desde el controlador*@
@Html.DropDownList("Combo2", "- Seleccione -")
@*Helper con valores desde una lista de objetos*@
@Html.DropDownList("Combo3", new SelectList(Model.ListaGenero, "id", "Nombre"))
@*Helper con valores desde una lista de objetos y atributos html*@
@Html.DropDownList("Combo4", new SelectList(Model.ListaGenero, "id", "Nombre"), new { style = "background-color:gray" })
@*Helper con valores desde un SelectListItem y etiqueta por defecto. Es posible colocar un valor por efecto con el atributo Selected*@
@Html.DropDownList("Combo5", new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = false, Text = "Novela", Value = "1"},
new SelectListItem { Selected = false, Text = "Cuento", Value = "2"},
new SelectListItem { Selected = false, Text = "Poema", Value = "3"},
new SelectListItem { Selected = true, Text = "Romance", Value = "4"}
}, "Value", "Text"), "Seleccione Género")
@*Helper con valores desde un array, con etiqueta por defecto y atributos html, nótese que se agregó un valor por defecto en el constructor del SelectList.*@
@Html.DropDownList("Combo6", new SelectList(new []{
new {id="1", Nombre="Novela"},
new {id="2", Nombre="Cuento"},
new {id="3", Nombre="Poema"},
new {id="4", Nombre="Romance"}
}, "id", "Nombre", 5), "- Seleccione -", new { style = "color:red" })
<br /><br />
@*Helper con valores desde una lista de objetos*@
@Html.DropDownListFor(m => m.Libro.Genero.id, new SelectList(Model.ListaGenero, "id", "Nombre"))
@*Helper con valores desde una lista de objetos y atributos html*@
@Html.DropDownListFor(m => m.Libro.Genero.id, new SelectList(Model.ListaGenero, "id", "Nombre"), new { id="ComboGenero2", style="color:green;"})
@*Helper con valores desde una lista de objetos, nótese que aunque se colocó un valor por defecto con el atributo Selected, éste se ignora y prevalece el valor asignado al modelo*@
@Html.DropDownListFor(m => m.Libro.Genero.id, new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = false, Text = "Novela", Value = "1"},
new SelectListItem { Selected = false, Text = "Cuento", Value = "2"},
new SelectListItem { Selected = false, Text = "Poema", Value = "3"},
new SelectListItem { Selected = true, Text = "Romance", Value = "4"},
new SelectListItem { Selected = false, Text = "Comedia", Value = "5"}
}, "Value", "Text"), "Selecciona")
@*Helper con valores desde una lista de objetos, nótese que aunque se colocó un valor por defecto en el constructor del SelectList y el atributo Selected, éstos se ignoran y prevalece el valor asignado al modelo*@
@Html.DropDownListFor(m => m.Libro.Genero.id, new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = false, Text = "Novela", Value = "1"},
new SelectListItem { Selected = false, Text = "Cuento", Value = "2"},
new SelectListItem { Selected = false, Text = "Poema", Value = "3"},
new SelectListItem { Selected = true, Text = "Romance", Value = "4"},
new SelectListItem { Selected = false, Text = "Comedia", Value = "5"}
}, "Value", "Text", 3), " - Seleccionar - ", new { id = "ComboGenero4", style = "background-color:yellow;" })<br />
Al ejecutar nuestro código nuestra vista se mostraría de la siguiente manera:
Ahora revisemos el codigo Html generado por nuestros ejemplos
<br /><br />
<select id="Combo1" name="Combo1">
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option value="5">Comedia</option>
<option value="6">Drama</option>
</select>
<select id="Combo2" name="Combo2">
<option value="">- Seleccione -</option>
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option value="5">Comedia</option>
<option value="6">Drama</option>
</select>
<select id="Combo3" name="Combo3">
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option value="5">Comedia</option>
<option value="6">Drama</option>
</select>
<select id="Combo4" name="Combo4" style="background-color:gray">
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option value="5">Comedia</option>
<option value="6">Drama</option>
</select>
<select id="Combo5" name="Combo5">
<option value="">Seleccione Género</option>
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
</select>
<select id="Combo6" name="Combo6" style="color:red">
<option value="">- Seleccione -</option>
<option value="1">Novela</option>
<option selected="selected" value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
</select>
<br /><br />
<select id="Libro_Genero_id" name="Libro.Genero.id">
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option selected="selected" value="5">Comedia</option>
<option value="6">Drama</option>
</select>
<select id="ComboGenero2" name="Libro.Genero.id" style="color:green;">
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option selected="selected" value="5">Comedia</option>
<option value="6">Drama</option>
</select>
<select id="Libro_Genero_id" name="Libro.Genero.id">
<option value="">Selecciona</option>
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option selected="selected" value="5">Comedia</option>
</select>
<select id="ComboGenero4" name="Libro.Genero.id" style="background-color:yellow;">
<option value=""> - Seleccionar - </option>
<option value="1">Novela</option>
<option value="2">Cuento</option>
<option value="3">Poema</option>
<option value="4">Romance</option>
<option selected="selected" value="5">Comedia</option>
</select>
Con esto espero que no tengan ningún problema en generar un combo con la ayuda del helper DropDownList, cualquier duda pueden hacerlo en los comentarios y gustosamente les contestaré. Recuerden que pueden descargar el código del post actual haciendo clic
aqui.