asp.net-mvc - MVC5应用程序: Create Identity User results in Invalid Model State?

标签 asp.net-mvc asp.net-mvc-5 entity-framework-6 asp.net-identity modelstate

我正在将开发中的应用程序从 MVC4/EF5 升级到 MVC5/EF6,以利用(除其他外)ASP.Net Identity。当我尝试创建用户时,我的代码将模型标记为无效并且不创建用户。我的 View 只是显示一个用于输入电子邮件的框,然后显示一个开关,让登录的管理员选择成员(member)组织或赞助商以通过一些下拉菜单分配新用户 2。

我的 UserController 的 Create() 方法如下:

        // GET: Admin/UserManagement/Create
        public ActionResult Create()
        {
            ViewBag.headerTitle = "Create User";
            ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name");
            ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name");
            ViewBag.SwitchState = true;
            ApplicationUser newUser = new ApplicationUser();
            newUser.RegisteredDate = DateTime.Now;
            newUser.LastVisitDate = DateTime.Now;
            newUser.ProfilePictureSrc = null;
            return View(newUser);
        }

        // POST: Admin/UserManagement/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Property1, Property2, etc.")] ApplicationUser applicationUser)
        {
            if (ModelState.IsValid)
            {
                ViewBag.headerTitle = "Create User";
                PasswordHasher ph = new PasswordHasher();
                var password = ph.HashPassword("aR@nD0MP@s$w0r9");
                var user = new ApplicationUser() { UserName = applicationUser.UserName, Email = applicationUser.Email, PasswordHash = password };
                IdentityResult result = await UserManager.CreateAsync(user, user.PasswordHash);
                if (result.Succeeded)
                {
                    await db.SaveChangesAsync();
                    return RedirectToAction("Index", "UserManagement");
                }
                else
                {
                    ModelState.AddModelError("", "Failed to Create User.");
                }
            }

            ModelState.AddModelError("", "Failed to Create User.");

            var errors = ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }).ToArray();

            var errors2 = ModelState.Values.SelectMany(v => v.Errors);

            ViewData["Organization"] = new SelectList(db.MemberOrganizations, "Id", "Name", applicationUser.MemberOrgId);
            ViewData["Sponsor"] = new SelectList(db.SponsorOrganizations, "Id", "Name", applicationUser.SponsorOrgId);
            if (applicationUser.MemberOrgId != null)
            {
                ViewBag.SwitchState = true;
            }
            else
            {
                ViewBag.SwitchState = false;
            }
            ViewBag.OrganizationId = new SelectList(db.MemberOrganizations, "Id", "State", applicationUser.MemberOrgId);

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

        }

在尝试调试该问题时,我按照 this 中的建议添加了 errors/errors2 变量。邮政。当这些被标记时,进入模型状态属性,我收到:

InvalidModelState1

InvalidModelState2

有人对这个问题有什么想法吗?我以前的代码运行良好,但我仍在适应 ASP.Net Identity。

编辑:根据 Rikard 的建议,我设置了模型,其中 SponsorOrgID 和 MemberOrgID 并不同时需要(只有 1 个)。现在我的代码向下处理,直到以下片段:

var user = new ApplicationUser() { Name = applicationUser.Name, Email = applicationUser.Email, PasswordHash = password };
                IdentityResult result = await UserManager.CreateAsync(user, user.PasswordHash);
if (result.Succeeded) // ERROR
{
    await db.SaveChangesAsync();
    return RedirectToAction("Index", "UserManagement");
}

当我检查 result 的值并深入查看 Errors->[string[]]->[0] 时,错误消息为:Name不能为 null 或为空。有人对此有什么想法吗?我在 View 中添加了一个字段来指定新用户 Name 并将其合并到上面的 new ApplicationUser() 代码行中。我不完全确定我在哪里遗漏了一些东西。

编辑2: Create()查看[相关]:

@model PROJECTS.Models.ApplicationUser

@{
    ViewBag.Title = "Create";
    Layout = "~/Areas/Admin/Views/Shared/_LayoutAdmin.cshtml";
    string cancelEditUrl = "/Admin/UserManagement/";
}

@using (Html.BeginForm("Create", "UserManagement", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.HiddenFor(model => model.RegisteredDate)

    <div class="container">

        <div class="row">
            <div class="editor-label">
                @Html.LabelFor(model => model.Name)
            </div>
            <div class="editor-field" style="margin-bottom: 15px">
                @Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Name)
            </div>
        </div>

        <div class="row">
            <div class="editor-label">
                @Html.LabelFor(model => model.Email)
            </div>
            <div class="editor-field" style="margin-bottom: 15px">
                @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Email)
            </div>
        </div>

....

最佳答案

正如您在最后一张图片中看到的,SponsorOrgId 属性上有一个错误,其值为 string.Empty ("")。也许 ApplicationUser 中的 SponsorOrgId 具有 [Requried] 属性。

编辑

关于尝试将用户添加到数据库时出现的问题(当您调用 UserManager.Create(user,password); 时会发生这种情况)

IdentityResult result = await UserManager.CreateAsync(user, user.PasswordHash);
if (result.Succeeded)
{
    await db.SaveChangesAsync();
    return RedirectToAction("Index", "UserManagement");
}
else
{
    var errors = string.Join(",", result.Errors);
    ModelState.AddModelError("", errors);
}

然后您可以调试“errors”的值或从 ModelState 中读取错误消息。

关于您的编辑

为此部分添加名称:

var user = new ApplicationUser() { UserName = applicationUser.UserName, Email = applicationUser.Email, PasswordHash = password, Name = applicationUser.Name };

编辑2 问题是没有用户名就无法创建用户。但您可以将用户的电子邮件添加到用户名中。然后将其更改为用户指定的用户名。为了使其通过验证,您需要添加这部分。

UserManager.UserValidator = new UserValidator<User>(UserManager) { RequireUniqueEmail = true };

关于asp.net-mvc - MVC5应用程序: Create Identity User results in Invalid Model State?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24042763/

相关文章:

asp.net-mvc - 如何在 Application Insights for ASP.NET MVC(.NET Full) 中临时停止记录 RequestTrackingTelemetryModule

c# - EF如何更新包含实体列表的实体

c# - 从数据库 MVC C# 中存储的路径下载 ZIP 文件

c# - 无法在 SignalR Send 中将 Viewbag 作为参数发送

c# - 在 Entity Framework 中重复创建和删除数据库

asp.net-web-api - OData V4修改服务器端$filter

c# - ASP.NET MVC 中的 <%# 和 <%= 有什么区别?

jquery - 按字母顺序显示下拉值

c# - MongoDB 计算某个项目在另一个表中被引用的次数

asp.net-mvc-5 - RavenDb 的 KeyNotFoundException