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

asp.net asp.net-mvc asp.net-mvc-4 c# entity-framework

Question

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..

1
5
12/15/2013 10:32:58 PM

Accepted Answer

  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.

3
6/9/2013 11:21:37 AM

Popular Answer

There are a few ways of addressign your problem (as described by user hutchonoid in his answer). I guess the best choice would be to not use your User as model for the edit view as it's obviously not its purpose in this case. Instead create a separate UserEditModel class containing all the user properties you'd like to have on your edit view and annotate them with proper validation attributes as you'd normaly do. Then in your edit view change the model form User to UserEditModel. In your controller you'll have something similiar to the code below:

[HttpGet]
public ActionResult Edit(int userId)
{
    var user = db.Users.SingleOrDefault(u => u.UserID == userId);
    if user != null)
    {
        return View(UserUpdatModel.FromUser(user));
    }
    // do whatever you do to handle errors
}

[HttpPost]
public ActionResult Edit(UserUpdateModel user)
{
    if (ModelState.IsValid)
    {
        var userToUpdate = db.Users.SingleOrDefault(u => u.UserID == user.UserID);
        if (userToUpdate != null)
        {
            // update fields in userToUpdate with data from user
            db.SaveChanges();
        }
    }
    // do whatever you do to handle errors
}

I've ommited some code for simplicity (like error handling or the content of UserEditModel - its properties and FromUser method which would create an instance of itself based on provided User). Hope that helps.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow