How to edit a user in ASP.NET Identity

前端 未结 2 559
耶瑟儿~
耶瑟儿~ 2020-12-29 17:41

I am new to the ASP.NET Identity framework and I am trying to do some things. What I want to do is to edit the user who has already register and then update the user details

相关标签:
2条回答
  • 2020-12-29 18:23

    Create a dbcontext object "context" and you also need to create a model class "UserEdit" and include those fields in it which you wants to edit.

    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");
        }
    

    // for deleting a user

    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");
                }
            }
    

    Below is the View for 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>
    

    // below is my UserEdit Model

     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; }
        }
    

    //below is my IdentityModel.cs class which have ApplicationDbContext class

    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();
            }
        }
    }
    

    Hope this help you :)

    0 讨论(0)
  • 2020-12-29 18:24

    There is a class that comes with asp.net identity called UserManager this class will help with the user information management you can first find a user using either

    • FindByIdAsync
    • FindByEmailAsync
    • FindByUserName

    with the user object, you can then update it with new information for the user profile

    and then use the method UpdateAsync to update the user information in the database.

    when it comes to getting a list of users you can use the IdentityDbContext class to get the list of users from.

    0 讨论(0)
提交回复
热议问题