gpt4 book ai didi

c# - ASP.Net MVC2 DropDownListFor

转载 作者:太空狗 更新时间:2023-10-29 21:25:27 25 4
gpt4 key购买 nike

我正在尝试在一个项目中学习 MVC2、C# 和 Linq to Entities(是的,我很生气),但我在使用 DropDownListFor 并将 SelectList 传递给它时遇到了一些问题。

这是我 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 获取 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") %>

对此很满意。

有人能帮忙吗?

最佳答案

编辑:那么您正在使用 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);
}

您的强类型 View 模型将是:

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

您的 View 代码将是:

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

关于c# - ASP.Net MVC2 DropDownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2749971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com