ASP.Net MVC2 DropDownListFor [英] ASP.Net MVC2 DropDownListFor

查看:185
本文介绍了ASP.Net MVC2 DropDownListFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学MVC2,C#和LINQ到实体都在同一个项目(是的,我是疯了),我遇到了一些问题,DropDownListFor和传球选择列表吧。

I am trying to learn MVC2, C# and Linq to Entities all in one project (yes, I am mad) and I am experiencing some problems with DropDownListFor and passing the SelectList to it.

这是在我的控制器中的code:

This is the code in my controller:

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 methodList时 ViewData的。当我尝试:

and I am having troubles trying to get the DropDownListFor to take the MethodList in ViewData. When I try:

<%:Html.DropDownListFor(model => model.method_id,new SelectList("MethodList","method_id","Description",Model.method_id)) %>

它的错误了以下消息

It errors out with the following message

DataBinding: 'System.Char' does not contain a property with the name 'method_id'.

我知道这是为什么,因为它正在 methodList时作为一个字符串,但我无法弄清楚如何得到它采取的SelectList 。如果我在一个正常的以下的DropDownList

I know why this is, as it is taking MethodList as a string, but I can't figure out how to get it to take the SelectList. If I do the following with a normal DropDownList:

<%: Html.DropDownList("MethodList") %>

有与此非常高兴。

谁能帮助?

推荐答案

修改:那么您使用的是实体框架,是吗?在你把注释中的另外信息的话,你会想要做这样的事情:

EDIT: So you are using Entity Framework, yes? In that case with the addition info you put in the comments, you would want to do something like this:

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

您强类型的视图模型将是:

Your strongly typed view model would be:

public class CreateViewModel
{
     public string SelectedMethod { get; set; }
     public IEnumerable<SelectListItem> Methods { get; set; }
}

您认为code将是:

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

这篇关于ASP.Net MVC2 DropDownListFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆