I’ve been looking at the ASP.NET MVC framework for the past two weeks, and it has occurred to me that some of the simple things we may want to do when creating a web application may seem confusing to someone new to ASP.NET MVC – for example the task of creating a DropDownList control on a form. ASP.NET MVC provides a number of ‘HTML Helpers’ which we can easily use to construct the form items. ‘DropDownList’ is one of these HTML helpers we can use.
Let’s create a simple example form using some of these HTML helpers. To begin a form, we can use a helper, we just need to add this code to our View:
// Form data will go here
<% } %>
This creates the basic form code for us – no need to explicitly write any HTML code. Before adding the DropDownList control, we need to decide where we want to get the data which will bind to the list. We can either hard code the items, or use LINQ to SQL to grab them from a database at runtime.
Method 1 – Hardcoding the form items
With this approach, we just add the items to a list, and pass this list to ViewData, so we can access it from the View:
Text = "Apple",
Value = "1"
Text = "Banana",
Value = "2",
Selected = true
Text = "Orange",
Value = "3"
ViewData["DDLItems"] = items;
Then, to actually display the DropDownList, we’d just need to add a single line to our View code, utilizing the DropDownList HTML helper:
Method 2 – Using LINQ to SQL to get the data at runtime
We could also retrieve the list data from a database table at runtime using LINQ to SQL. In order for this approach to work, you will need to have generated LINQ to SQL classes for your database using the wizard in Visual Studio. Then we can easily write the code to retrieve the data:
var db = new TransDBDataContext();
IEnumerable<SelectListItem> languages = db.trans_SupportedLanguages
.Select(c => new SelectListItem
Value = Convert.ToString(c.ID),
Text = c.Name.ToString()
ViewData["SupportedLanguages"] = languages;
Again, to display the DropDownList, we’d just need to add a single line of code to the View:
From the above, you can see how easy it is to render form items using the HTML helpers provided by ASP.NET MVC.
For a full list of the helpers, check out the MSDN documentation here.