Create a new ASP.NET MVC Web Application;
Right-click on the Models folder and select Add > New Item;
From the Add New Item dialog, select LINQ to SQL classes. Name it MyModel.dbml and click Add;
Picture 1 - Create a new LINQ to SQL file
Select the connection you want to use on the Server Explorer Window, expand it and select the tables you want to use;
Drag and drop them onto the dbml file surface. For this example I am using a database that has two tables: Product and Category;
Picture 2 - Product and categories tables added to the dbml file
Right-click the Controllers folder and select Add > Controller. Name it ProductController and hit the Add button;
Picture 3 - New controller class
A new controller class is created it. Open it. We are going to add an action method called Selector that will perform a LINQ query to retrieve a list of products. We are going to save it to the ViewData dictionary and request a view to be rendered;
public class ProductController : Controller
{
MyModelDataContext _ctx = new MyModelDataContext();
public ActionResult Selector()
{
var products = from prod in _ctx.products
select prod;
ViewData["ProductList"] = products;
return View();
}
}
Right-click the action method we’ve just created and select Add View (or just press ctrl + M, V). On the Add View dialog, name it Selector and keep the first two checkboxes unchecked. Hit the Add button;
Picture 4 - Create the View for our selector
On the View we are going to use the DropdownList HtmlHelper method to render the dropdownlist control using the list of products added to the ViewData dictionary by our Selector action method. The object used to bind an IEnumerable object to a dropdownlist control is the SelectList. There an explanation about it on http://ittecture.wordpress.com/2009/04/21/tip-of-the-day-189-aspnet-mvc-dropdownlists/. We are going also to add a submit button so we can catch the selected item on the controller class. The Html markup will be similar to the following:
<% using (Html.BeginForm()) { %>
<%= Html.DropDownList(“lstProducts”, new SelectList((IEnumerable)ViewData["ProductList"], “ID”, “Name”)) %>
<input type=”submit” value=”Submit” />
<% } %>
Let’s add an action method that handles the post actions on this view so we can catch the selected product id:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Selector(FormCollection form)
{
/// Gets the selected product.
int productID = Convert.ToInt32(form["lstProducts"]);
[...]
}
Build and run the application. Navigate to http://localhost:<Port Number>/Product/Selector . The dropdownlist control is loaded and displays the product name.
Picture 5 - The product selector in action
You may hit the submit button and check the product id on the Selector action method that handles the post action.