asp.net-mvc ModelState.IsValid 总是返回 false

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13373935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:24:51  来源:igfitidea点击:

ModelState.IsValid is always returning false

asp.net-mvcasp.net-mvc-3modelstate

提问by Mizbella

[HttpPost]
public ActionResult Create(Users user)
{
    if (ModelState.IsValid)
    {
        db.Users.Add(user);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }

    return View(user);
}

ModelState.IsValidis always false.
so it just return view and new record is not getting added..

ModelState.IsValid总是假的。
所以它只是返回视图并且没有添加新记录..

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; }
}

回答by gdoron is supporting Monica

ModelState.IsValidwill be false if the validation for the Model failed.

ModelState.IsValid如果模型验证失败,则为 false。

  1. You have DataAnnotationwhich failed the incoming model.
  2. You added custom validations.
  3. Make sure there are no null entries in the model for non null properties
  1. 您的DataAnnotation使传入模型失败。
  2. 您添加了自定义验证。
  3. 确保模型中没有非空属性的空条目

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

检查ModelState.Errors导致这种情况的原因是什么。你可以使用这个:

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