【问题标题】:Model State Is Not Valid But Why? [duplicate]模型状态无效但为什么呢? [复制]
【发布时间】:2017-07-27 00:30:42
【问题描述】:

在“创建”页面上提交 POST 时,我正在返回查看,并且调试已将其范围缩小到模型状态无效,但我不确定它为什么无效。

这就是我想要做的。我添加了一个要上传的文件,该文件在 create 方法中运行良好,直到我需要从下拉菜单中添加更多详细信息。最初,当我只需要文件时,它看起来像这样:

public ActionResult Create(HttpPostedFileBase file)
        {
            ViewBag.EnvironmentTypeId = new SelectList(db.environmenttypes, "EnvironmentTypeId", "EnvironmentTypeName", 1);
            if (ModelState.IsValid)
            {
                IO io = new IO();
                if (file != null)
                {
                    AppUpdate updateLog = io.UpdateApp(file, env.EnvironmentTypeId);
                    updateLog.UserName = User.Identity.Name;
                    updateLog.EnvironmentTypeId = env.EnvironmentTypeId;
                    db.appupdates.Add(updateLog);
                    db.SaveChanges();
                }
                else
                {
                    return RedirectToAction("Create");
                }
                return RedirectToAction("Index");
            }

            return View();
        }

所以我在模型中添加了更多内容以获取详细信息:

public ActionResult Create([Bind(Include="EnvironmentTypeId")] AppUpdate env, HttpPostedFileBase file)
        {
            ViewBag.EnvironmentTypeId = new SelectList(db.environmenttypes, "EnvironmentTypeId", "EnvironmentTypeName", 1);
            if (ModelState.IsValid)
            {
                IO io = new IO();
                if (file != null)
                {
                    AppUpdate updateLog = io.UpdateApp(file, env.EnvironmentTypeId);
                    updateLog.UserName = User.Identity.Name;
                    updateLog.EnvironmentTypeId = env.EnvironmentTypeId;
                    db.appupdates.Add(updateLog);
                    db.SaveChanges();
                }
                else
                {
                    return RedirectToAction("Create");
                }
                return RedirectToAction("Index");
            }

            return View();
        }

为什么这里无效?它出什么问题了?如果我在标记之前遗漏了更多未添加的详细信息,请先告诉我。

【问题讨论】:

  • 无法判断您何时不显示模型或ModelState 错误
  • @DavidG 如果他知道模型状态错误,他就不会在这里了:D
  • @JoePhillips 的确如此。虽然我打赌这是由于 Bind 不包括需要验证的属性。
  • 就是这样,它是一个必填字段,不是字段,也不是页面上尚未填写的字段。我需要稍后填写,但它需要它。

标签: c# asp.net-core-mvc


【解决方案1】:

ModelState 有一个属性可以准确地告诉您它为什么无效。使用它。

这是一个带有示例的答案:Get error message if ModelState.IsValid fails?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-18
    • 2020-06-17
    • 2017-06-09
    • 2016-05-07
    相关资源
    最近更新 更多