Editing user profile details

前端 未结 2 1182
感情败类
感情败类 2021-02-11 02:57

How to create action and views for editing user custom informations?

Authorization is based on membership created by VS with MVC 4 project.

I\'ve added additiona

2条回答
  •  再見小時候
    2021-02-11 03:50

    So you want an edit page for editing personal information of user. Additional columns are already added to UserProfile table.

    First of all you need an actionmethod for edit view. Fetch the user from database and build your UserProfileEdit model.

    public ActionResult Edit()
    {
                string username = User.Identity.Name;
    
                // Fetch the userprofile
                UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.Equals(username));
    
                // Construct the viewmodel
                UserProfileEdit model = new UserProfileEdit();
                model.FirstName = user.FirstName;
                model.LastName = user.LastName;
                model.Email = user.Email;
    
                return View(model);
    }
    

    When we post the editform, we post UserProfileEdit model. We fetch the UserProfile from database again and change the posted fields.

        [HttpPost]
        public ActionResult Edit(UserProfileEdit userprofile)
        {
            if (ModelState.IsValid)
            {
                string username = User.Identity.Name;
                // Get the userprofile
                UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.Equals(username));
    
                // Update fields
                user.FirstName = userprofile.FirstName;
                user.LastName = userprofile.LastName;
                user.Email = userprofile.Email;
    
                db.Entry(user).State = EntityState.Modified;
    
                db.SaveChanges();
    
                return RedirectToAction("Index", "Home"); // or whatever
            }
    
            return View(userprofile);
        }
    

    Now it's just coding in your view. Mine looks like this:

    @model UserProfileEdit
    
    @using (Html.BeginForm("Edit", "Account"))
    {
        @Html.EditorFor(model => model.FirstName)
         @Html.EditorFor(model => model.LastName)
         @Html.EditorFor(model => model.Email)
    
        
    }
    

    Automapper might help if you have tons of fields for your edit model. This solution edits the current logged in user but adding username as action parameter is rather trivial.

提交回复
热议问题