【问题标题】:ModelState isvalid return false when id / key = 0当 id / key = 0 时,ModelState isvalid 返回 false
【发布时间】:2020-01-13 09:06:06
【问题描述】:

当创建时主键为 0 时,ModelState Isvalid 返回 false。

在模型中:

[Key]
        public int CourseId { get; set; }

在数据库中:

数据库数据:

在视图中:

值为 0:

ModelState IsValid 返回 false:

知道为什么它无效吗?

【问题讨论】:

  • 使用单独的视图模型。
  • 什么意思?
  • stackoverflow.com/a/4633032/5394220 它适用于aspnet MVC,但想法是一样的。不过,不确定如何在 NetCore 中归档 Bind(Exclude=..) 之类的内容。
  • 它已经是一个视图模型,[key]在模型中,并且模型定义在一个视图模型中,与另一个模型。

标签: c# asp.net-core data-annotations required modelstate


【解决方案1】:

试试这个方法。不要返回空值,而是返回 Course 的新实例

  public ViewResult AddCourse(int id)
  {
        var course = yourservice.GetById(id);

        if(customer == null)
        {
            course = new Course();
        }
        return View(course);
    }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2016-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多