0

I am new to the asp.net MVC 5 identity framework andI am try to do update my details directly. Straight forward, What I want to do is to update my user information to the database. Previously, I changed my user details by using Migrations and I use entity framework in order to generate my controller, view and model it self. However, How do I update my user details. I have seen role methods..but I never understand, How can I do? without using role..Because, I want to update all of user information that I needed to do it in UserManageController...

Is it possible? in a different controller and getting values directly on generated user account? How to retrieve then?

Here is my Identity 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 string userFname { get; set; }
        public string userLname { get; set; }
        public string address { get; set; }
        public string userContactNo { get; set; }
        public string commercialName { get; set; }
        public string commercialAddress { get; set; }
        public string commercialEmail { get; set; }
        public string userType { get; set; }

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

Here is my Registeration model

public class RegisterViewModel
{
    [Required]
    [Display(Name = "User First Name")]
    public string userFname { get; set; }

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

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

    [Required]
    [Display(Name = "User Contact Number")]
    public string userContactNo { get; set; }

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

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

    [EmailAddress]
    [Display(Name = "Commercial Email")]
    public string commercialEmail { get; set; }

    [Key]
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    [Required]        
    public string userType { get; set; }

}
7
  • This question looks similar to yours. Commented Apr 12, 2017 at 9:26
  • Please visit the below link , It may help you : stackoverflow.com/questions/43362226/… Commented Apr 12, 2017 at 10:00
  • Did you check my answer @HamunSunga ?? This is waht you are expecting. Commented Apr 12, 2017 at 10:22
  • Possible duplicate of How to edit a user in ASP.NET Identity Commented Apr 12, 2017 at 10:23
  • @Basanta Matia - yeh, but I want direct access, not using a different model ...I am asking, can I get the model class which has auto generated itself in order to generate my edit? is it possible? Commented Apr 12, 2017 at 10:33

2 Answers 2

1

How I do this,

UPDATED: As he commented in my answer bellow, he want to update a list of users in the same method. So this will work.

[HttpPost]
public async Task<ActionResult> UpdateUserInfo(List<RegisterViewModel> model)
{
  if (!ModelState.IsValid)
    {
        return View(model);
    }

    var userStore = new UserStore<ApplicationUser>(new 
                                  ApplicationDbContext());
    var appManager = new UserManager<ApplicationUser>(userStore);

    // here you can do a foreach loop and get the email and assign new datas
    foreach(var i in model)
     {
       var currentUser = appManager.FindByEmail(i.Email);

       // here you can assign the updated values
       currentUser.userFname = i.userFname;
       // and rest fields are goes here
       await appManager.UpdateAsync(currentUser);
     }
    var ctx = userStore.Context;
    ctx.SaveChanges();
    // now you can redirect to some other method or-else you can return 
    // to this view itself by returning the data

    return RedirectToAction("SomeActionMethod");
}

And yes, you should have the fields in your view and there will be a @Html.BeginForm and a submit button to post your data. Or-else you can post by ajax method

Hope it helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please tell me how to retrieve a list of users as well..Your answer perfectly works for me, but I want a list of users as well thats y......@Basanta Matia
Check my updated answer above, you can update list of user now...cheers
0

Assuming that your ApplicationUser class is part of your Entity Framework DBContext, you can retrieve and update a user like so, using Entity Framework;

var userId = "user id here"; // Set a user ID that you would like to retrieve

var dbContext = new YourDbContext(); // Your entity framework DbContext

// Retrieve a user from the database
var user = dbContext.Set<ApplicationUser>().Find(userId);

// Update a property on your user
user.address = "New value";

// Save the new value to the database
dbContext.SaveChanges();

If you need the userId of the current logged in user, use:

var userId = this.User.Identity.GetUserId();

Multiple users can be retrieved and updated like this:

var dbContext = new YourDbContext();

// Get all users
var users = dbContext.Set<ApplicationUser>().ToList();

foreach (var user in users)
{
   user.address = "New value";
}

// Save the new value to the database
dbContext.SaveChanges();

Entity framework will automatically track the changes to each for when you save.

3 Comments

Can I get a list of users I mean not passing direct id
Thank you very much you also help me a lot..thanks for that...:)
No problem. Feel free to give it a cheeky vote up :o)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.