正确的方法是使用 ViewModels。基本上,您必须为您的视图创建一个视图模型,而不是将数据库结果直接传递给您的视图。就像是:
public class PersonViewModel
{
public Person Person {get ; set;}
public Dictionary<int, string> AgeGroups { get; set; }
public PersonViewModel() {}
public PersonViewModel(int personId)
{
var ctx = new Context();
this.Person = ctx.Persons.SingleOrDefault(p => p.Id == personId);
foreach(var ageGroup in ctx.AgeGroups)
{
this.AgeGroups.Add(ageGroup.Id, ageGroup.AgeGroupName);
}
}
然后您的控制器方法将如下所示:
public ActionResult Add(PersonViewModel vm)
{
var ctx = new Context();
if(ModelState.IsValid)
{
ctx.Persons.Add(vm.Person);
return View("Index");
}
return View(vm);
}
在您看来,简单地说:
@Html.DropDownListFor(model => model.Person.AgeGroupId,
new SelectList(model.AgeGroups, "Id", "AgeGroupName"))
当然,您的视图模型现在是PersonViewModel.
更新
似乎 ASP.NET MVC 3 工具更新默认为关系添加下拉菜单。更多信息在这里。