Model is not valid in the edit time in asp.net MVC

Sep 25 2018 4:59 AM
Hi,
 
i am getting error when i'm trying to edit the data in MVC 
here is my model class
 
[Table("tblUser")]
public class User
{
[Key]
public int Id { get; set; }
public string FirstName { get; set; }
[Required]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[NotMapped]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
public string Salt { get; set; }
[ForeignKey("Role")]
public int RoleId { get; set; }
public Role Role { get; set; }
[ForeignKey("Department")]
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
 
Confirm password, i do not want to store in the database so i given [NotMapped] 
 
i think here is the main problem ... because their is no problem in the time of user creation , but when im trying to edit those user that it is not updating , the control is not going inside of 
if (ModelState.IsValid)
{
}
 
, in the edit time from the view i remove Password , ConfirmPassword ,Salt because i dont want to edit this three field , may be because of that this model is not valid in the time of edit .
 
here is the code 
 
[HttpPost]
public ActionResult Edit(int id, User user)
{
var entity = db.User.Find(id);
user.Username = entity.Username;
user.Password = entity.Password;
user.Salt = entity.Salt;
// user.ConfirmPassword = entity.ConfirmPassword;
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.DepartmentId = new SelectList(db.Department, "Id", "Name", user.DepartmentId);
ViewBag.RoleId = new SelectList(db.Roles, "Id", "Name", user.RoleId);
return RedirectToAction("Index");
}
 
i do not know exactly why error is coming always please someone help me !

Answers (2)