加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – MVC 4 DropDownListFor错误 – 没有具有密钥的

发布时间:2020-12-15 20:37:05 所属栏目:asp.Net 来源:网络整理
导读:我有一个模特: public class Auction{ public string Title { get; set; } public string category { get; set; }} 和控制器: [HttpGet]public ActionResult UserForm(){ var categoryList = new SelectList(new[] { "auto","elec","games","Home" }); Vie
我有一个模特:
public class Auction
{
    public string Title { get; set; }
    public string category { get; set; }
}

和控制器:

[HttpGet]
public ActionResult UserForm()
{

    var categoryList = new SelectList(new[] { "auto","elec","games","Home" });
    ViewBag.categoryList = categoryList;
    return View();

}

在视图中我有以下几行:

<div class="editor-field">
    @Html.DropDownListFor(model =>
        model.category,(SelectList)ViewBag.categoryList)
    @Html.ValidationMessageFor(model => model.category)

</div>

我尝试保存表单时遇到的错误是:

There is no ViewData item of type ‘IEnumerable’ that
has the key ‘category’. Description: An unhandled exception occurred
during the execution of the current web request. Please review the
stack trace for more information about the error and where it
originated in the code.

Exception Details: System.InvalidOperationException: There is no
ViewData item of type ‘IEnumerable’ that has the key
‘category’.

我不明白是什么问题,因为我做了(或试图做)本指南中完成的所有事情:
https://www.youtube.com/watch?v=7HM6kDBj0vE

该视频也可以在此链接中找到(第6章 – 自动绑定到请求中的数据):
http://www.lynda.com/ASPNET-tutorials/ASPNET-MVC-4-Essential-Training/109762-2.html

解决方法

The error i get when i try to save the form

这就是你的问题所在.我怀疑你没有在post方法中重建你的列表. get方法中的以下代码行也应该在post方法中,特别是如果要返回相同的视图,或者在下拉列表中使用ViewBag.categoryList的视图.

var categoryList = new SelectList(new[] { "auto","Home" });
ViewBag.categoryList = categoryList;

当您使用带有dropdownlistfor html帮助器的null对象时,会出现这种错误.如果您执行类似的操作,则可以轻松复制该错误

@Html.DropDownListFor(model => model.PropertyName,null)
// or
@Html.DropDownList("dropdownX",null,"")

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读