Nothing wrong with the answers offered so far but I'm going to give you a different approach. Bellow you will find code that defines an extension method to any IEnumerable of T. These extension methods convert any list to a SelectList:
namespace System
{
public static class IEnumerableExtensions
{
public static SelectList ToSelectList<T>(this IEnumerable<T> items) where T : class
{
return new SelectList(items);
}
public static SelectList ToSelectList<T>(this IEnumerable<T> items, object selectedValue) where T : class
{
return new SelectList(items, selectedValue);
}
public static SelectList ToSelectList<T>(this IEnumerable<T> items, string dataValueField, string dataTextField, object selectedValue) where T : class
{
return new SelectList(items, dataValueField, dataTextField, selectedValue);
}
public static SelectList ToSelectList<T>(this IEnumerable<T> items, string dataValueField, string dataTextField) where T : class
{
return new SelectList(items, dataValueField, dataTextField);
}
}
}
Because they are defined in System namespace, these methods will be available to you anywhere in your code. You can now do the following:
Model.GetItemList().ToSelectList();
or
Model.GetItemList().ToSelectList("ValueFieldName", "TextFieldName");
So now you can just pass your list as part of your view model:
public class MyViewModel
{
// Replace T here with your domain model fetched from Model.GetItemList()
public List<T> Items { get; set; }
}
public ActionResult Name()
{
// Previous action logic here...
var myViewModel = new MyViewModel { Items = Model.GetItemList() }
return View(myViewModel);
}
and then in your view you can now do this:
// Declare your view model at the top of your view
@model yournamespace.MyViewModel
// Define your drop down list.
@Html.DropDownListFor(n => n.Value, Model.Items.ToSelectList());