Altaf Khatri
Find me on web
► Orkut
How to bind IList with MVC Dropdownlist box?
I am a big fan of IList, a System.Collections.Generic interface.
It is convenient to use IList in many situations, when the object needs to be iterated without knowing the length, type of the repeating object using foreach loop and a var datatype.
IList inherits IEnumerable interface and hence it inherits all the good things associated with it. To associate IList with the MVC dropdownlist is simple. I will discuss 2 methods:
Method 1:
Perform the following actions in the MVC Controller
- Create IList of SelectListItem type.
IList<SelectListItem> iliSLI = new List<SelectListItem>(); -
Create an object of type SelectListItem and assign the text and value properties;
SelectListItem sli = new SelectListItem();
sli.Text = "What is your Mother's maiden name?";
sli.Value = "1";
sli.Selected = true; -
Add the object created above to the IList collection. You can loop through the list of items retrieved from the
database and add the object to the IList collection.
iliSLI.Add(sli); - Create as many item as you want to appear in the dropdownlist box following the steps above.
- Assign the IList to the ViewData with the same name as the dropdownlist box. In this case "SecretQuestion"
ViewData["SecretQuestion"] = iliSLI;
<%= Html.DropDownList("SecretQuestion")%>
Method 2: - Here we will be using the database to retrieve data using the stored procedure. I am getting data from the stored procedure named:
udp_GetSecretQuestionlist. This stored procedure returns me the following columns:
- pkSecretQuestion
- SecretQuestionDetail
- dtCreated
- CreatedBy
- UpdatedOn
- UpdatedBy
IList<tbl_SecretQuestion> iltblSecretQuestions = null;where TaskManagerEntities is my DataEntity Framework's class.
using (TaskManagerEntities tme = new TaskManagerEntities())
{
iltblSecretQuestions = tme.udp_GetSecretQuestionlist().ToList();
}
and tbl_SecretQuestion is the entity class associated as the output of the stored procedure. -
Now selecting the required columns for the binding with the MVC Dropdownlist
ViewData["SecretQuestion"] = new SelectList(iltblSecretQuestions, "pkSecretQuestion", "SecretQuestionDetail", "2");where textField = SecretQuestionDetail
valueField = pkSecretQuestion and
the last parameter 2 represents the Question for which the pkSecretQuestion = 2 and not the second item in the list. -
In the View of the page use the following MVC Html helper:
<%= Html.DropDownList("SecretQuestion")%>
