如何在MVC 3中使用Entity Framework绑定dropdownList

时间:2013-05-20 08:53:30

标签: c# asp.net-mvc asp.net-mvc-3 entity-framework-4 html.dropdownlistfor

我想在我的dropdownList应用中使用Entity Framework在页面上显示MVC,但我只是坚持使用HTML帮助来完成此操作。所以,如果有人了解实体框架,请帮助我...

我的dataContext分部类为Entities,其中名为MemberInfo的实体包含一些字段,包括MemberID& MemberName,因此我的dropdownList应显示字段MemberName&在此背后,该值应为MemberID

我试过的代码--->

@Html.DropDownListFor(Model => Model.MemberID, MemberInfo)

在控制器中我返回模型--->

var MemberNameList = FinanceDBContext.MemberInfoes.Select(x => new { x.MemberID, x.Name });
return View(MemberNameList);  

但它不起作用(errors)。

1 个答案:

答案 0 :(得分:2)

您需要将所有对象作为“模型”传递。最佳做法是使用 ViewModel ,其中包含数据列表和存储所选项目的属性。

<强>视图模型

public class MyViewModel
{
    // The drop-down list and variable to get selection
    public List<Member> Members { get; set; }
    public int SelectedMemberId { get; set; }
}

<强>控制器

[HttpGet]
public ActionResult Index()
{
    var viewModel = new MyViewModel();
    viewModel.Members = FinanceDBContext.MemberInfoes.ToList();
    return View(viewModel);
}

[HttpPost]
public ActionResult Index(MyViewModel viewModel)
{
    string debug = string.Format("You selected member: {0}", viewModel.SelectedMemberId);
    return View(viewModel);
}

最后,在您的视图中(这些行必须位于BeginForm {...}内,并确保您的视图强类型为MyViewModel

@Html.DropDownList("SelectedMemberId", new SelectList(Model.Members, "MemberID", "Name"))
<input type="submit" value="Save etc..." />

在此示例中,您可以在HttpPost操作上设置一个断点,并检查调试字符串以检查是否返回了正确的成员并按要求继续操作。