Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid certain fields to be updated in model using asp.net mvc 4

I am new to asp.net mvc 4 and EF. I am creating User Model which creates/updates user info. The code for model is as follows:

....
public int UserID { get; set; }

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

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

[Compare("Password")]   
public string VerifyPassword { get; set; }
.....
 SOME OTHER FIELDS COMES HERE
......

This same model used for create/update activity. This works fine for create user but while updating i don't want user to update his Id, username so I keep it readonly also don't want to show user password/verify password fields so I removed it from view. Now while updating(Edit mode) I am always getting validation error message for password field. So my question is how do I avoid updating these fields and do update for other fields. To solve this problem I try to create viewmodel but it doesn't help me. Also added code for bypassing validation like this in controller:

public ActionResult Edit(User user)
{
   ModelState.Remove("Password");
   ModelState.Remove("VerifyPassword");
   ModelState.Clear();
   if (ModelState.IsValid)
   {
     db.Entry(user).State = EntityState.Modified;
     db.SaveChanges();
     return RedirectToAction("Index");
   }
}

This give me ModelState.IsValid = true but fails to update. Please give me solution to this problem.

Thanks in advance..

like image 602
CodeWarrior Avatar asked Oct 21 '22 08:10

CodeWarrior


1 Answers

  1. You could manually set the fields that you are updating only and save the changes.

  2. You could reset the values taken from your database first. Something like the following (please forgive any errors)

    var userFromDb = db.Users.Where(u => u.UserID == user.UserID).First();
    user.Password = person.Password;
    user.VerifyPassword = person.VerifyPassword;
    
    db.Entry(person).CurrentValues.SetValues(user);
    db.SaveChanges();
    
  3. Create a custom model binder that only updates the relevant fields.

like image 89
hutchonoid Avatar answered Oct 31 '22 22:10

hutchonoid