ModelState.IsValid总是返回false [英] ModelState.IsValid is always returning false

查看:1064
本文介绍了ModelState.IsValid总是返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

    return View(user);
}

ModelState.IsValid 永远是假的。结果
所以它只是返回不获取添加的视图和新的记录。

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

推荐答案

ModelState.IsValid 将是错误的,如果对于模型验证失败。

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


  1. 您有 DataAnnotation 而无法进入的模式。

  2. 您添加的自定义的验证。

  3. 确保有在模型中没有空项非空的属性

  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

检查 ModelState.Errors 什么是造成这种情况的原因。您可以使用此:

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

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

这篇关于ModelState.IsValid总是返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆