In this tutorial I'll show you how you can easily load values to a DropDownList so your users can choose from a range of options.
In this tutorial, I'm making some assumptions:
- You are familiar with the MVC pattern.
- You have at least read about what the ViewData[] dictionary is.
- You are familiar with Linq-to-SQL. [Not excluding!]
Imagine that you want to display a list of Areas available so your end user can choose from them.
Assuming you already have your Linq-to-SQL .dbml file created and ready to go, create a class called AreaRepository.cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DropDownListExample { public class AreaRepository { private YourDataContext db = new YourDataContext(); public IQueryable<Area> FindAllAreas() { return db.Areas; } } }
The above method will return an IQueryable object that you can use to query specific areas. We won't be doing any fancy though.
Now, in your AreaController, let's create an Action called Create. We want to create a new Room. A Room 'belongs to' an Area, hence the need to display a DropDownList of available Areas.
Do the following in your Create Action method:
public ActionResult Create() { Room room = new Room(); AreaRepository area = new AreaRepository(); ViewData["Areas"] = new SelectList(area.FindAllAreas().ToList(), "ID", "Name"); return View(area); }
Let's break down what we've done.
We create a new Room object using the .dbml automatically generated Room class.
Then we instantiated the AreaRepository class we created in the beginning so we could access the .FindAllAreas() method so we could have a list of all Areas in our database.
We use the .ToList() method to return a nice List. We then say the ID field of Area will be the value member, and Name field will be the display member.
REMEMBER: ID and Name are fields that exist in the tables! Unfortunately, Visual Studio doesn't help us with intellisense in this regard.
We then save this List of Areas to the ViewData[] dictionary!
So far so good. We have a list of Areas, and it is saved in the ViewData[] dictionary.
Create your Create view and set it to be a strongly-typed view for Room.
In your Create.aspx view, you need to add the following code and that wraps it up!
<%: Html.DropDownList("IDJefe", (SelectList)ViewData["Areas"]) %>
I hope you enjoyed this tutorial. Any questions please feel free to ask and I'll update this tutorial.