The problem I’m having right now it’s that ASP.NET MVC validates the request object, user in this case
public ActionResult Edit(User user)
What I want to do is that if the user’s password is left blank, do not update the password, just use the old password, but if it’s set, update it.
The problem is that the framework complains that user does not has a password, even if I update the user object, it complains
public ActionResult Edit(User user)
{
user.Password = "Something";
// more code...
}
Apparently it does the validation on the request object, is there a way I can skip the validation in this case, or at least delay it until I finished modifying the user object?
This is the full method code
[HttpPost]
public ActionResult Edit(User user)
{
if (string.IsNullOrEmpty(user.Password))
{
var oldUser = db.Users.Single(u => u.Id == user.Id);
user.Password = oldUser.Password;
}
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(user);
}
}
The model state will still be invalid even after you set the password to something. After you do that try clear the model state using
ModelState.Clear();Or modify the ModelState accordingly i.e clear the error state only for password propertyModelState.Remove("Password");From your posts it looks like you are ware of the
[Required]attribute on the password field. I suggest you force javascript validation and let the user know that they cannot update the password to be blank. Or if you are updating User information in a form that doesn’t include password create a new viewmodel or temp model that does not have the password field and the model is specific to that form. Post to this model and bind to this model. Then update the actual user model by using the data from the temp user model. This will be better practice to follow.