【问题标题】:There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'UserName'没有具有键“用户名”的“IEnumerable<SelectListItem>”类型的 ViewData 项
【发布时间】:2014-02-08 17:59:25
【问题描述】:

没有具有键“用户名”的“IEnumerable”类型的 ViewData 项。 在视图中有 2 个下拉列表 - 对于用户和角色,提交后我需要为选择的用户保存角色。有角色一切都很好,但用户有问题。我在列表中有用户列表,但我无法读取为 db 选择的内容。如果使用 Html.TextBox("UserName") - 它可以工作,但管理员会手动编写用户名,这不好。 我不是 MVC 方面的专家,所以感谢任何帮助。 控制器:

    UsersContext db = new UsersContext();

    public ActionResult Index()
    {
        SelectList list = new SelectList(Roles.GetAllRoles());
        ViewBag.Roles = list;

        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var user in db.UserProfiles.ToList())
        {
            SelectListItem li = new SelectListItem
            {
                Value = user.UserName,
                Text = user.UserName
            };
            items.Add(li);
        }

        ViewBag.UserName = items;

        return View(db.UserProfiles.ToList());
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string RoleName, string UserName)
    {

        SelectList list = new SelectList(Roles.GetAllRoles());
        ViewBag.Roles = list;
        return View();
    }

Model是SimpleMembershipprovider,是用project创建的。

查看:

 @model IEnumerable<UserProfile>
 @Html.DropDownList("UserName", ViewBag.UserName as SelectList) - here mistake

我应该怎么解决?

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    问题在于下面的代码 -

    public ActionResult Index(string RoleName, string UserName)
    {
        SelectList list = new SelectList(Roles.GetAllRoles());
        ViewBag.Roles = list;
        return View();
    }
    

    在上面的代码中,您从未启动过 - ViewBag.UserName,但您的视图需要 ViewBag 中的 UserName 属性(您只启动了角色)。你启动它,问题就会解决。

    【讨论】:

      【解决方案2】:

      这样做:

      ViewBag.cityid = new SelectList(db.hr_pr_cities, "CityID", "Name");
      

      这样的观点:

      @Html.DropDownList("cityid", null, "Select City", null)
      

      【讨论】:

        【解决方案3】:

        试试这个:

        @model IEnumerable<UserProfile>
        @Html.DropDownList("UserName",new SelectList(ViewBag.UserName, "Value", "Text"))
        

        或者把你的UserName的类型改成SelectList然后在这里修改:

        ViewBag.UserName = new SelectList(items, "Value", "Text");
        //instead of ViewBag.UserName = items;
        

        【讨论】:

          【解决方案4】:

          项目类型是List&lt;SelectListItem&gt;,而不是SelectList。试试:

          ViewBag.UserName as List<SelectListItem>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-03-23
            • 2015-04-26
            • 2020-06-28
            • 2020-08-20
            • 2011-02-20
            相关资源
            最近更新 更多