[HttpPost]
public ActionResult Create(Users user)
{
if (ModelState.IsValid)
{
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
ModelState.IsValid
is always false.
so it just return view and new record is not getting added..
Edit
User:
public class User
{
public int UserID { get; set; }
public string Name { get; set; }
[Display(Name = "Confirm Password")] [DataType(DataType.Password)]
public string ConfirmPassword { get; set; }
public string Designation { get; set; }
[Display(Name = "Date of Join")] [DataType(DataType.Date)] public DateTime DOJ { get; set; }
public string Email { get; set; }
[Display(Name = "Phone Number")] public System.Int64 PhoneNo { get; set; }
}
IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.
If you want to remove only the errors you could loop through all elements in the ModelState and for each element remove the errors that might be associated to it. Once you do that, ModelState. IsValid will become true .
ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.
AddModelError("Region", "Region is mandatory"); ModelState. IsValid will then return false.
ModelState.IsValid
will be false if the validation for the Model failed.
Check the ModelState.Errors
for what is the reason causing this. You can use this:
var errors = ModelState.Values.SelectMany(v => v.Errors);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With