无法将ViewData绑定到下拉列表

时间:2015-06-18 18:05:42

标签: c# asp.net-mvc simplemembership viewdata

我正在开发一个asp.net mvc 4应用程序,我正在尝试为管理员添加删除用户功能,我可以从下拉列表中选择一个用户并删除他。

private static IEnumerable<SelectListItem> getUsers()
        {
            WhiteBoardAppContext db = new WhiteBoardAppContext();
            IEnumerable<SelectListItem> numbers = (from i in db.UserProfiles                           
                           select new SelectListItem
                           { Text= i.UserName,
                           Value=i.UserId.ToString()
                           });
            return numbers.ToList();
        }


        [Authorize(Roles = "Admin")]
        public ActionResult DeleteUser()
        {
          var list = (IEnumerable<SelectListItem>)ViewData["UserList"];
           list = getUsers();          

            return View();
        }

 [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult DeleteUser(UserProfile model)
        {



            if (ModelState.IsValid)
            {

                try
                {
                    if (model.UserName == null)
                    {
                        TempData["ErrorMessage"] = "Username required.";
                        return RedirectToAction("Register", "Account");
                    }
                    else
                    {

                        var user = Membership.GetUser(model.UserName);
                        if (user == null)
                        {
                            TempData["ErrorMessage"] = "User Does Not exist.";
                            return RedirectToAction("Register", "Account");
                        }
                        else
                        {
                            Membership.DeleteUser(model.UserName);

                        }
                        return RedirectToAction("Register", "Account");
                    }
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

DeleteUser.cshtml

@model WhiteBoardApp.Models.UserProfile


@using (Html.BeginForm("DeleteUser", "Account"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    <fieldset>
        <div class="container-fluid">
            <ol>
                <li>

                    @Html.LabelFor(m => m.UserName)
                     @Html.DropDownList("UserList", (IEnumerable<SelectListItem>)ViewData["UserList"])
                    <span style="color:red;">@TempData["ErrorMessage"]</span>
                </li>

            </ol>
            <input type="submit" value="Delete User" />
            </div>
</fieldset>
}

但是,上面的代码告诉了我There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'UserList'.

我可以知道我哪里错了吗?

1 个答案:

答案 0 :(得分:1)

您需要将用户添加到ViewData词典:

[Authorize(Roles = "Admin")]
public ActionResult DeleteUser()
{
     ViewData["UserList"] = getUsers();       
     return View();
}

此外,您对DropDownList帮助程序的使用是错误的,因为第一个参数应该是包含所选用户的输入名称,而不是选择列表本身。

在您的情况下var list = (IEnumerable<SelectListItem>)ViewData["UserList"];将返回null,因此没有实际的分配。

但总的来说,我会建议您不要使用ViewData,而是创建一个VieModel并将所有必需的数据放在那里:

public class DeleteUserViewModel
{
    public IList<SelectListItem> UserList {get;set;}

    public int SelectedUserId {get;set;}
} 

控制器:

[Authorize(Roles = "Admin")]
[HttpGet]
public ActionResult DeleteUser()
{
     var model = new DeleteUserViewModel{
        UserList = getUsers()
     };      
     return View(model);
}

[HttpPost]
public ActionResult DeleteUser(DeleteUserViewModel model)
{
     int userToDelete = model.SelectedUserId;
     //delete user logic here
}

查看:

@model WhiteBoardApp.Models.DeleteUserViewModel


@using (Html.BeginForm("DeleteUser", "Account"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()

<fieldset>
    <div class="container-fluid">
        <ol>
            <li>

                @Html.LabelFor(m => m.UserName)
                @Html.DropDownListFor(m=>m.SelectedUserId, Model.UserList )
                <span style="color:red;">@TempData["ErrorMessage"]</span>
            </li>

        </ol>
        <input type="submit" value="Delete User" />
        </div>
</fieldset>
}