繁体   English   中英

ASP.Net MVC2 DropDownListFor

[英]ASP.Net MVC2 DropDownListFor

我试图在一个项目中学习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);
} 

我正在努力让DropDownListForViewData获取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) %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM