如何在ASP.NET标识中编辑用户

4 c# asp.net-mvc entity-framework asp.net-mvc-4

我是ASP.NET身份框架的新手,我正在尝试做一些事情.我想要做的是编辑已注册的用户,然后将用户详细信息更新到数据库...以前,我使用实体框架,然后生成我的控制器视图并自行建模.但我想更新我的用户详细信息并将用户列表添加到列表中..

我该怎么做这些东西?我见过角色方法..但我从不明白,我该怎么办?没有使用角色..因为我不需要管理员的目的.只是,我想更新我的用户详细信息.

Pra*_*rya 11

创建dbcontext对象"context",您还需要创建一个模型类"UserEdit",并在其中包含您要编辑的那些字段.

private ApplicationDbContext context = new ApplicationDbContext();
// To view the List of User 
 public ActionResult ListUsers ()
        {
            return View(context.Users.ToList());
        }

public ActionResult EditUser(string email)
        {
            ApplicationUser appUser = new ApplicationUser();
            appUser = UserManager.FindByEmail(email);
            UserEdit user = new UserEdit();
            user.Address = appUser.Address;
            user.FirstName = appUser.FirstName;
            user.LastName = appUser.LastName;
            user.EmailConfirmed = appUser.EmailConfirmed;
            user.Mobile = appUser.Mobile;
            user.City = appUser.City;


            return View(user);
        }

    [HttpPost]
    public async Task<ActionResult> EditUser(UserEdit model)
    {


        if (!ModelState.IsValid)
        {
            return View(model);
        }
        var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
        var manager = new UserManager<ApplicationUser>(store);
        var currentUser = manager.FindByEmail(model.Email);
        currentUser.FirstName = model.FirstName;
        currentUser.LastName = model.LastName;
        currentUser.Mobile = model.Mobile;
        currentUser.Address = model.Address;
        currentUser.City = model.City;
        currentUser.EmailConfirmed = model.EmailConfirmed;
        await manager.UpdateAsync(currentUser);
        var ctx = store.Context;
        ctx.SaveChanges();
        TempData["msg"] = "Profile Changes Saved !";
        return RedirectToAction("ListUser");
    }
Run Code Online (Sandbox Code Playgroud)

//用于删除用户

public ActionResult DeleteUser(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = context.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(context.Users.Find(id));
        }


        public async Task<ActionResult> UserDeleteConfirmed(string id)
        {
            var user = await UserManager.FindByIdAsync(id);

            var result = await UserManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                TempData["UserDeleted"] = "User Successfully Deleted";
                return RedirectToAction("ManageEditors");
            }
            else
            {
                TempData["UserDeleted"] = "Error Deleting User";
                return RedirectToAction("ManageEditors");
            }
        }
Run Code Online (Sandbox Code Playgroud)

以下是ListUser的视图:

@model IEnumerable<SampleApp.Models.ApplicationUser>

@{
    ViewBag.Title = "ListUsers";
}

<div class="row">
    <div class="col-md-12">
        <div>
            <h3>@ViewBag.Message</h3>
        </div>
        <div>
            <h2>ManageEditors</h2>


            <table class="table">
                <tr>
                    <th>
                        S.No.
                    </th>
                    <th>
                        Email
                    </th>
                    <th>
                     EmailConfirmed
                    </th>

                    <th>
                       FirstName
                    </th>
                    <th>
                       LastName
                    </th>
                    <th>
                        Mobile
                    </th>
                    <th></th>
                </tr>
                @{ int sno = 1;
                   foreach (var item in Model)
                {
                    <tr>
                        <td>
                         @(sno++)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Email)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.EmailConfirmed)
                        </td>

                        <td>
                            @Html.DisplayFor(modelItem => item.FirstName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.LastName)
                        </td>
                        <td>
                            @Html.DisplayFor(modelItem => item.Mobile)
                        </td>
                        <td>
                            @Html.ActionLink("Edit", "EditUser", new { email=item.Email})
                            @Html.ActionLink("Delete", "DeleteUser", new { id = item.Id })
                        </td>
                    </tr>
                }
}
            </table>


        </div>
    </div>

</div>
Run Code Online (Sandbox Code Playgroud)

//下面是我的UserEdit模型

 public class UserEdit
    {
        [Display(Name = "Email")]
        public string Email { get; set; }

        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }


        [Display(Name = "Mobile")]
        public string Mobile { get; set; }


        [Display(Name = "Address")]
        public string Address { get; set; }


        [Display(Name = "City")]
        public string City { get; set; }

        public bool EmailConfirmed { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

//下面是我的IdentityModel.cs类,它有ApplicationDbContext类

using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace SampleApp.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
        //Extra column added to auto generated Table by Code First approach (ASPNETUSERS) by Entity Framework
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string DOB { get; set; }
        public string Sex { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Mobile { get; set; }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助:)

  • 完成`await manager.UpdateAsync(currentUser)`后,无需调用`ctx.SaveChanges()`.UserManager已经为您完成此操作. (3认同)

Rah*_*oon 5

有一个名为UserManager 的asp.net 身份附带的类, 这个类将有助于用户信息管理,您可以首先使用以下任一方法找到用户

  • FindByIdAsync
  • FindByEmail异步
  • 按用户名查找

使用用户对象,然后您可以使用用户配置文件的新信息更新它

然后使用 UpdateAsync 方法更新数据库中的用户信息。

在获取用户列表时,您可以使用IdentityDbContext类从中获取用户列表。