SelectList
is an Html helper from Asp.net which can be passed a group of parameters to achieve what you want without having to spend so much work. You must read the parameters that it accepts and you will understand its operation. example:
SelectList(System.Collections.IEnumerable items, string dataValueField, string dataTextField, object selectedValue, string dataGroupField);
The 1st parameter is a collection of objects (they are all the objects that will be shown in the dropdown of your HTML view, here you can declare up to a LINQ query that returns a list).
The 2nd parameter is an example string: "id" and it is the value that you will pick when selecting an object from the drop-down, in this case the Id.
The 3rd parameter is another string and represents the text that will be displayed for each object in the dropdown in your HTML view. example "Name".
The 4th will show an item selected by default. (Very used in the Edit view where you must show the value that this object already has by default)
The 5th to define the group to which it belongs in case groups are defined. (Personally I have not worked much with this parameter).
Once explained this I give you an example so that you see it clearer.
Assuming you have a class Filtro
with the attributes id
and nombre
where Id stores the values (1,2,3 ..) and name ("Active", "Rejected", "Pending" ...) or simply a list called Filters with those values and you need to show them in your HTML as a Select
drop down. just define it in your controller as follows:
ViewBag.filtrado = new SelectList(db.Filtros(),"Id", "Nombre");
and in your view as you had it declared, making sure that the names of the ViewBag and the first parameter of the HTML Helpler match.
@Html.DropDownList("filtrado", null, "Filtrar por", htmlAttributes: new { @class = "form-control", @id = "filtro" })
This way when displaying the select, the names of the filters will be shown, but when you select them, you will pass the Id as a value. I hope it will be helpful.