Hadeel e

Hadeel e

  • NA
  • 50
  • 6.5k

Update user profile in MVC 5

Apr 28 2020 10:14 PM
Hi, I am using identitiy framework to my existing application (I added it after I start working with the login).
Generally, I was using my own database. Right Now, I have the user inserted in 2 tables 1- my own table 2- aspnetUsers table. 
 
As a resule, when I try to update or display user profile I use the identity user to generate that information. 
However, when the user login and try to access the profile view, I'm getting an error that the "UserName" parameter cann't be null. 
 
How Would I generate the user information in this case?
My action function looks as the following:
  1. [HttpGet]  
  2.        public async Task <ActionResult> UpdateDriverProfile()  
  3.        {  
  4.   
  5.            var user = User.Identity.Name;  
  6.            var userStore = new UserStore<IdentityUser>();  
  7.            var userManager =  new UserManager<IdentityUser>(new UserStore<IdentityUser>(new RidesDbContext()));  
  8.   
  9.             
  10.   
  11.            DriversModel driver = new DriversModel();  
  12.            IdentityUser theUser = new IdentityUser()  
  13.             
  14.            {  
  15.              UserName = driver.email,  
  16.              Email = driver.email  
  17.            };  
  18.   
  19.            driver.email = theUser.UserName;  
  20.            driver.email = theUser.Email;  
  21.            driver.phoneNumber = theUser.PhoneNumber;  
  22.            driver.PasswordHash = theUser.PasswordHash;  
  23.            driver.userID = theUser.Id;  
  24.   
  25.            var store = await userStore.FindByNameAsync(theUser.UserName);  
  26.            theUser = await userManager.FindByNameAsync(driver.email);  
  27.   
  28.   
  29.            DriversTier tier = new DriversTier();  
  30.            driver = tier.getDriverByUserID(driver.userID);  
  31.            return View("UpdateDriverProfile", driver);  
  32.   
  33.        } 
 just to make things clear, this is how I rwgister or add the user to the database:
  1.      
  2. [HttpPost]  
  3.        public async Task<ActionResult> DriversRegistration(DriversModel driver, IEnumerable<HttpPostedFileBase> images)  
  4.        {  
  5.            var profileImg = images.ElementAt(0);  
  6.            var licenseImg = images.ElementAt(1);  
  7.  
  8.            //First check the first Image  
  9.            if (profileImg != null && profileImg.ContentLength > 0)  
  10.            {  
  11.                driver.profileImgType = profileImg.ContentType;  
  12.                string fileName = profileImg.FileName;  
  13.                string pattern = @"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";  
  14.   
  15.                Regex rgx = new Regex(pattern);  
  16.   
  17.                //Get the length of the image in bytes and create that array  
  18.                driver.profileImg = new byte[profileImg.ContentLength];  
  19.   
  20.                //fill the array of bytes with the image data  
  21.                profileImg.InputStream.Read(driver.profileImg, 0, profileImg.ContentLength);  
  22.   
  23.                //Need to do model state checking here, provided some code for that already  
  24.   
  25.                ModelState.Clear();  
  26.   
  27.            }  
  28.            //Now check the second Image  
  29.            if (licenseImg != null && licenseImg.ContentLength > 0)  
  30.            {  
  31.                driver.licenseImgType = licenseImg.ContentType;  
  32.                string fileName = licenseImg.FileName;  
  33.                string pattern = @"([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";  
  34.   
  35.                Regex rgx = new Regex(pattern);  
  36.   
  37.                //Get the length of the image in bytes and create that array  
  38.                driver.licenseImg = new byte[licenseImg.ContentLength];  
  39.   
  40.                //fill the array of bytes with the image data  
  41.                licenseImg.InputStream.Read(driver.licenseImg, 0, licenseImg.ContentLength);  
  42.   
  43.                //Need to do model state checking here, provided some code for that already  
  44.   
  45.                ModelState.Clear();  
  46.   
  47.            }  
  48.   
  49. if (ModelState.IsValid)  
  50.            {  
  51.   
  52.                bool processError = false;  
  53.                var userStore = new UserStore<IdentityUser>();  
  54.                var userManager = new UserManager<IdentityUser>(userStore);  
  55.                string statusMessage = "";  
  56.                IdentityUser theUser = new IdentityUser() {  
  57.                    UserName = driver.email,  
  58.                    Email = driver.email,  
  59.                    PasswordHash = driver.PasswordHash,  
  60.                    PhoneNumber = driver.phoneNumber  
  61.                      
  62.                    };  
  63.                IdentityResult theResult = await userManager.CreateAsync(theUser,driver.PasswordHash);  
  64.                var store = await userStore.FindByNameAsync(theUser.UserName);  
  65.                theUser = await userManager.FindByNameAsync(driver.email);  
  66.                string UserName = theUser.UserName;  
  67.                string password = theUser.PasswordHash;  
  68.                string Email = theUser.Email;  
  69.                string phoneNumber = theUser.PhoneNumber;  
  70.                string userID = theUser.Id;  
  71.                driver.userID = userID;  
  72.                DriversTier tier = new DriversTier();  
  73.                int newID = tier.insertDriver(driver);  
  74.                driver.driverId = newID;  
  75.   
  76.                if (theResult == IdentityResult.Success)  
  77.                {  
  78.                    //First check to see if User Role exists.  If not create it and add user to User role.  
  79.   
  80.                    if (driver != null)  
  81.                    {  
  82.                        var roleStore = new RoleStore<IdentityRole>();  
  83.                        var roleManager = new RoleManager<IdentityRole>(roleStore);  
  84.                        var therole = new IdentityRole("Driver");  
  85.                        theResult = await roleManager.CreateAsync(therole);  
  86.   
  87.                        if (theResult == null)  
  88.                        {  
  89.                            statusMessage = string.Format("User Group Creation failed because : {0}", theResult.Errors.FirstOrDefault());  
  90.                            //Need to exit nicely here for some reason, we could not create the role with the DB  
  91.                            processError = true;  
  92.                        }  
  93.                    }  
  94.   
  95.                    if (!processError)  
  96.                    {  
  97.                        //The role exists, now add the user to the role  
  98.                        theResult = await userManager.AddToRoleAsync(theUser.Id, "Driver");  
  99.                        statusMessage = string.Format("Identity User {0} was created successfully!<br /> {0} was added to the User group: {1}", theUser.UserName, theResult.Errors.FirstOrDefault());  
  100.                    }  
  101.                      
  102.                }  
  103.                else  
  104.                {  
  105.                    //could not create a user  
  106.                    statusMessage = string.Format("User Creation failed because : {0}", theResult.Errors.FirstOrDefault());  
  107.                    processError = true;  
  108.                }  
  109.   
  110.                List<IdentityUser> userList = userManager.Users.ToList<IdentityUser>();  
  111.                return RedirectToAction("ThankYou""Default");  
  112.            }  
  113.            else  
  114.            {  
  115.                return View();  
  116.            } 
 and this is the model I'm using for both registration and the profile:
 
  1. public class DriversModel  
  2. {         
  3.     [Key]  
  4.         [Display(Name ="Id")]  
  5.         public int driverId { getset; }  
  6.         //this is the FK associated with the aspnetusers table  
  7.         public string userID { getset; }  
  8.   
  9.         [Display(Name = "First Name")]  
  10.         [Required(ErrorMessage = "Pleas Enter Your First Name")]  
  11.         public string firstName { getset; }  
  12.   
  13.         [Display(Name = "Last Name")]  
  14.         [Required(ErrorMessage = "Pleas Enter Your Last Name")]  
  15.         public string lastName { getset; }  
  16.   
  17.         [Display(Name = "Email Address")]  
  18.         [DataType(DataType.EmailAddress)]  
  19.         [Required(ErrorMessage = "Pleas Enter Your Email Address")]  
  20.         [RegularExpression(".+\\@.+\\..+", ErrorMessage = "Please Enater a Valid Email Address")]  
  21.         public string email { getset; }  
  22.   
  23.         [Display(Name = "Mobile Number")]  
  24.         [Required(ErrorMessage = "Pleas Enter Your Mobile Number")]  
  25.         public string phoneNumber { getset; }  
  26.   
  27.         [Display(Name = "Address")]  
  28.         [Required(ErrorMessage = "Pleas Enter Your Address")]  
  29.         public string Address { getset; }  
  30.   
  31.         [Display(Name = "City")]  
  32.         [Required(ErrorMessage = "Pleas Enter Your City")]  
  33.         public string city { getset; }  
  34.   
  35.         [Display(Name = "State")]  
  36.         [Required(ErrorMessage = "Pleas Enter Your state")]  
  37.         public string state { getset; }  
  38.   
  39.         [Display(Name = "Car")]  
  40.         [Required(ErrorMessage = "Please Identify Your Car")]  
  41.         public string car { getset; }  
  42.   
  43.         [Display(Name = "Driver's License")]   
  44.         [Required(ErrorMessage = "Please Enter Your Driver's Licende Number")]  
  45.         public string driverslicense { getset; }  
  46.   
  47.   
  48.         [Display(Name ="Profile Image")]  
  49.         [Required]  
  50.         public byte[] profileImg { getset; }  
  51.   
  52.         public string profileImgType { getset; }  
  53.   
  54.         [Display(Name = "License Image")]  
  55.         [Required]  
  56.         public byte[] licenseImg { getset; }  
  57.   
  58.         public string licenseImgType { getset; }  
  59.   
  60.        [Display(Name ="Password")]  
  61.        [DataType(DataType.Password)]  
  62.        [Required(ErrorMessage ="Please Enter a password")]  
  63.        public string PasswordHash { getset; }  
  64.          
  65.        [Display(Name = "Username")]  
  66.        public string UserName { getset; }  
  67.           
  68.   
  69. }  
  70.   

 
I would appreciate your help. Thank You.
 

Answers (7)