asp.net mvc dropdownlist 没有 ViewData 项

发布于 2024-08-22 13:44:41 字数 227 浏览 2 评论 0原文

我开始学习mvc,尝试添加下拉列表,进行构建

<%= Html.DropDownList("ddl") %>

,但它显示错误

不存在具有键“ddl”的“IEnumerable”类型的 ViewData 项

为什么?我使用简单的代码,只传递名称参数,那么为什么会出现错误?

i start to study mvc, try to add dropdownlist, make construction

<%= Html.DropDownList("ddl") %>

but it show error

There is no ViewData item of type 'IEnumerable' that has the key 'ddl'

why? i use simple code, only pass name parameter, so why the error?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

横笛休吹塞上声 2024-08-29 13:44:41

实际上,Html.DropDownList 是一个 HTML 帮助器,用于创建 html select 元素。当您传递 ddl 作为参数时,它期望获得一个数组或列表或类似的东西(实现 IEnumerable 接口的对象)来填充下拉列表。尝试这样:

在控制器中:

ViewData["ddl"]=new string[]{'Jan',  'Feb','Mar','Apr'.......'Dec'};

然后它将创建一个包含给定值的选择元素。有关详细信息,请阅读 这篇文章

Actually Html.DropDownList is an HTML helper that create html select element. When you pass ddl as argument it expects to get an array or list or something like that (an object implementing IEnumerable interface) to populate the dropdownlist. try it like this:

In Controller:

ViewData["ddl"]=new string[]{'Jan',  'Feb','Mar','Apr'.......'Dec'};

then it will create a select element containing the given values. For more information read this article.

清欢 2024-08-29 13:44:41
"There is no ViewData item of type 'IEnumerable'"

这意味着辅助方法需要一个类型为 'IEnumerable' 的项目,例如带有 Id 'ddl'List<>

如果您正在尝试显示一个 DropDownList,其中包含来自某些静态源的项目,这是一种方法。

          // create new IEnummerable 
          List<string> ddl = 
          new List<string>(new [] {"item1","item2" };   

          // add Items        
          ddl.Add("Item1");
          ddl.Add("Item2");

          // return View which holds ddl now
          ViewData["ddl "] = ddl ;
          return View();

有关更多见解,请查看

"There is no ViewData item of type 'IEnumerable'"

It means that helper method is expecting an item of type 'IEnumerable' for e.g, List<> with an Id 'ddl'

If you are trying to display a DropDownList which has items from some static source, here is one way to do this.

          // create new IEnummerable 
          List<string> ddl = 
          new List<string>(new [] {"item1","item2" };   

          // add Items        
          ddl.Add("Item1");
          ddl.Add("Item2");

          // return View which holds ddl now
          ViewData["ddl "] = ddl ;
          return View();

For more insight have a look at

此岸叶落 2024-08-29 13:44:41

这里是在 ASP.NET-MVC 中添加 DropDownList 的示例。您需要在 ViewData 中提供一个带有键“dll”的“IEnumerable”类型的项目,如错误所示。

Here is an example of adding a DropDownList in ASP.NET-MVC. You need to provide an item of type 'IEnumerable' with a key 'dll' in the ViewData, as the error says.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文