c# – ASP.Net MVC2 DropDownListFor
发布时间:2020-12-15 08:29:08 所属栏目:百科 来源:网络整理
导读:我试图在一个项目中学习MVC2,C#和 Linq到实体(是的,我很生气),我遇到了一些DropDownListFor问题,并将SelectList传递给它. 这是我的控制器中的代码: public ActionResult Create(){ var Methods = te.Methods.Select(a = a); ListSelectListItem MethodList
我试图在一个项目中学习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) %> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |