我试图在一个项目中学习MVC2,C#和
Linq到实体(是的,我很生气),我遇到了一些DropDownListFor问题,并将SelectList传递给它.
这是我的控制器中的代码:
public ActionResult Create() { var Methods = te.Methods.Select(a => a); List<SelectListItem> MethodList = new List<SelectListItem>(); 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.当我尝试:
<%:Html.DropDownListFor(model => 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执行以下操作:
<%: Html.DropDownList("MethodList") %>
对此非常满意.
有人可以帮忙吗?
解决方法
编辑:所以你正在使用实体框架,是吗?在这种情况下,您在评论中添加了添加信息,您可能希望执行以下操作:
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<SelectListItem> Methods { get; set; } }
您的查看代码将是:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<Createviewmodel>" %> <%-- Note the Generic Type Argument to View Page! --%> <%: Html.DropDownListFor(m => m.SelectedMethod,Model.Methods) %>