繁体   English   中英

使用ApplicationUser类更新用户数据-ASP.NET Identity

[英]Updating user data with ApplicationUser class - ASP.NET Identity

我有一个针对用户的“编辑”页面,该页面适用于GET,但对于POST而言,AplicationUser对象未保存在数据库中。 我提到有些对象字段为null,但已成功将其传递给POST方法。

我尝试为与数据库列相对应的每个属性分配一个值,以防if语句为null,但这并没有解决问题,也没有错误。
我发现这篇文章中的更新用户数据 -ASP.NET Identity第二个答案(JoshdeVries)可能与我的情况有关。

对象处于调试模式的照片

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit([Bind(Include = "Id,Name,Email,Password,ConfirmPassword,Roles,PhoneNumber")] ApplicationUser editUserModel)
    {
        if (ModelState.IsValid)
        {

            var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
            var manager = new UserManager<ApplicationUser>(store);
            var result manager.Update(editUserModel);
            if (!result.Succeeded) // This is false, so Update Failed!
            {
                Console.WriteLine(result.Errors.ToList());
                return View(editUserModel);
            } 
            store.Context.SaveChanges();
            return RedirectToAction("UsersList");
        }
        return View(editUserModel);
    }

在View 3这样的输入字段中(我需要填写更多字段,但是这3个字段用于测试):

<div class="form-group">
        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
        </div>
</div>

<div class="form-group">
        @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

<div class="form-group">
        @Html.LabelFor(model => model.PhoneNumber, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })
        </div>
    </div>

[PS]到目前为止,我已经应用了并且运行良好的解决方案:

{
        if (editUserModel.UserName == null)
        {
            editUserModel.UserName = editUserModel.Email;
        }
        if (ModelState.IsValid)
        {
            db.Entry(editUserModel).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("UsersList");
        }
        return View(editUserModel);
}

出于某种原因,在我看来,“ UserName”是某种密钥,对于标识用户行是必不可少的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM