Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModelState.IsValid is always returning false [duplicate]

[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; }
}
like image 1000
Mizbella Avatar asked Nov 14 '12 06:11

Mizbella


People also ask

Why is my ModelState IsValid false?

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.

How do you set ModelState IsValid to true?

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 .

What exactly does ModelState IsValid do?

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.

How do you make a ModelState IsValid false?

AddModelError("Region", "Region is mandatory"); ModelState. IsValid will then return false.


1 Answers

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);
like image 58
gdoron is supporting Monica Avatar answered Oct 05 '22 20:10

gdoron is supporting Monica