ASP.Net MVC2 DropDownListFor
我试图在一个项目中学习MVC2,C#和Linq到实体(是的,我很生气)我遇到了DropDownListFor的一些问题并将SelectList传递给它。
这是我的控制器中的代码:
public ActionResult Create() { var Methods = te.Methods.Select(a => a); List MethodList = new List(); foreach (Method me in Methods) { SelectListItem sli=new SelectListItem(); sli.Text = me.Description; sli.Value = me.method_id.ToString(); MethodList.Add(sli); } ViewData["MethodList"] = MethodList.AsEnumerable(); Talkback tb = new Talkback(); return View(tb); }
我试图让DropDownListFor
在ViewData
获取MethodList
,我遇到了麻烦。 当我尝试:
model.method_id,new SelectList("MethodList","method_id","Description",Model.method_id)) %>
它出错以及以下消息
DataBinding: 'System.Char' does not contain a property with the name 'method_id'.
我知道为什么会这样,因为它将MethodList
作为一个字符串,但我无法弄清楚如何让它采取SelectList
。 如果我使用普通的DropDownList
执行以下操作:
对此非常满意。
有人可以帮忙吗?
编辑 :所以你正在使用entity framework,是吗? 在这种情况下,您在评论中添加了添加信息,您可能希望执行以下操作:
public ActionResult Create() { var viewModel = new CreateViewModel(); // Strongly Typed View using(Entities dataModel = new Entities()) // 'te' I assume is your data model { viewModel.Methods = dataModel.Methods.Select(x => new SelectListItem() { Text = x.Description, Value = x.method_id.ToString() }); } return View(viewModel); }
您的强类型视图模型将是:
public class CreateViewModel { public string SelectedMethod { get; set; } public IEnumerable Methods { get; set; } }
您的查看代码将是:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <%-- Note the Generic Type Argument to View Page! --%> <%: Html.DropDownListFor(m => m.SelectedMethod, Model.Methods) %>