You can do two things:
a) The quick hack
public ActionResult Create() {
ViewData["myList"] = new SelectList( listOfCategories, "Name","CategoryId");
return View()
}
Create.aspx
...
<%= Html.DropDown("categoryId", ViewData["myList"] as SelectList,"-");
...
b) Create a ViewDataModel.
public class CreateProductViewData
{
public Product product { get; private set; };
public SelectList Categories { get; private set; }
public CreateProductViewData(Product p) {
product = p;
Categories = new SelectList( listOfCategories, "Name","CategoryId");
}
}
public ActionResult Create()
{
Product p = new Product() { name="New Product..." } ;
return View(new CreateProductViewData(p));
}
in Create.aspx
...Inherits="System.Web.Mvc.ViewPage<CreateProductViewData>" %>
..
..
<%= Html.DropDown("CategoryId", Model.Categories, "-");
I mostly use approach B, because it moves alot of code out of the controller, and into the "What is needed to display this page"-code, without cluttering the "HOW do i display the data" code.
So in effect I have
- Code that acts (the controller)
- Code that prepares the view, by loading secondary data (The ViewData object)
- Code that renders the view (the .aspx)
Usually I can reuse the ViewDataModel for both Edit and Create.