我是MVC的新手。我遇到验证错误的问题,因为我检查了所有数据库字段,我没有发现任何问题,但我仍然收到一个或多个实体验证失败的错误。我无法找到验证错误。
这是我的数据库架构:
public partial class make
{
public int make_id { get; set; }
public int category_id { get; set; }
public string title { get; set; }
public string imagePath { get; set; }
public virtual category category { get; set; }
}
以下是我的观点:
@model globalEngineProject.make
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Home", "make", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>category</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.title, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.title)
@Html.ValidationMessageFor(model => model.title)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.category_id, "category_id", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("category_id", String.Empty)
@Html.ValidationMessageFor(model => model.category_id)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.imagePath, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input name="file" type="file" id="file"/>
@Html.ValidationMessageFor(model => model.imagePath)
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Home([Bind(Include = "make_id,category_id,title")] make make, HttpPostedFileBase file)
{
try
{
if (ModelState.IsValid)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/images/"), fileName);
file.SaveAs(path);
}
db.makes.Add(make);
db.SaveChanges();
}
ViewBag.category_id = new SelectList(db.categories, "category_id", "category_name", make.category_id);
return View(make);
// return View("Index");
}
catch (RetryLimitExceededException )
{
//Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(make);
}
答案 0 :(得分:0)
要扩展Stephen的评论,看起来您没有为imagePath
设置值。要检查这一点,您可以在控制器方法中放入以下代码,以找出验证错误的详细信息:
var modelErrors = new List<ModelError>();
foreach (ModelState modelState in ViewData.ModelState.Values) {
foreach (ModelError error in modelState.Errors) {
modelErrors.Add(error);
}
}
这将为您提供调试时可以检查的ModelError
列表。这应该给你一个指向哪个字段有错误的指针。