Csharp/C#教程:ASP.Net MVC2 DropDownListFor分享


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); } 

我试图让DropDownListForViewData获取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; } } 

您的查看代码将是:

上述就是C#学习教程:ASP.Net MVC2 DropDownListFor分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 <%@ 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) %> 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1026730.html

(0)
上一篇 2022年1月9日
下一篇 2022年1月9日

精彩推荐