模型状态无效但为什么?

时间:2017-07-26 16:28:58

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

我在“创建”页面上提交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();
        }

为什么这里无效?它有什么问题?如果我错过了在标记之前我还没有添加的更多详细信息,请先告诉我。

1 个答案:

答案 0 :(得分:4)

ModelState有一个属性可以告诉您它为何无效。使用它。

以下是一个示例的答案:Get error message if ModelState.IsValid fails?