C# 模型状态无效,但原因是什么?
当我在创建页面上提交文章时,我得到了一个返回视图,调试将其缩小到模型状态无效,但我不确定它为什么无效 这就是我要做的。我添加了一个要上传的文件,该文件在create方法中运行良好,直到我需要从下拉菜单中添加更多细节。最初,当我只需要文件时,它看起来是这样的:C# 模型状态无效,但原因是什么?,c#,asp.net-core-mvc,C#,Asp.net Core Mvc,当我在创建页面上提交文章时,我得到了一个返回视图,调试将其缩小到模型状态无效,但我不确定它为什么无效 这就是我要做的。我添加了一个要上传的文件,该文件在create方法中运行良好,直到我需要从下拉菜单中添加更多细节。最初,当我只需要文件时,它看起来是这样的: public ActionResult Create(HttpPostedFileBase file) { ViewBag.EnvironmentTypeId = new SelectList(db.
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
有一个属性,它会准确地告诉您它无效的原因。用那个
下面是一个示例回答:不显示模型或
ModelState
errors@DavidG如果他知道modelstate错误,他就不会在这里了:D@JoePhillips是的,的确如此。虽然我打赌这是因为绑定
排除了需要验证的属性。这就是它的本质,它是一个必填字段,在页面上不是字段,也没有填写,直到稍后。我需要稍后再填写,但它想马上填写。