33
[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; }
}
Balagurunathan Marimuthu
  • 2,927
  • 4
  • 31
  • 44
Mizbella
  • 936
  • 2
  • 15
  • 30

1 Answers1

108

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);
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • is this code to be wriiten inside if(ModelState.IsValid) – Mizbella Nov 14 '12 at 06:36
  • 1
    @user1697789. No, it's a simple code to give you the error in the modelState, put it above the `if (ModelSatate.IsValid)`. – gdoron Nov 14 '12 at 06:38
  • 11
    +1 for var errors = ModelState.Values.SelectMany(v => v.Errors); – NoWar May 26 '13 at 21:24
  • 3
    Paste `ModelState.Values.SelectMany(v => v.Errors).ElementAt(0);` into the `immediate window`. – Jess Aug 04 '17 at 15:49
  • Is this still supposed to work? "errors" is null for me, but I just looked at the ModelState in the debugger, I could view the errors directly. – Heinzlmaen Nov 02 '20 at 16:03