ModelState.IsValid is always returning false

Mizbella picture Mizbella · Nov 14, 2012 · Viewed 49.9k times · Source
[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; }
}

Answer

gdoron is supporting Monica picture gdoron is supporting Monica · Nov 14, 2012

ModelState.IsValid will be false if the validation for the Model failed.

  1. You have DataAnnotation which failed the incoming model.
  2. You added custom validations.
  3. Make sure there are no null entries in the model for non null properties

Check the ModelState.Errors for what is the reason causing this. You can use this:

var errors = ModelState.Values.SelectMany(v => v.Errors);