C# 使用ASP.NET MVC和Razor时,一个或多个实体的验证失败

C# 使用ASP.NET MVC和Razor时,一个或多个实体的验证失败,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我是MVC新手。我在检查所有数据库字段时发现验证错误,但在那里没有发现任何问题,并且仍然收到一个或多个实体验证失败的错误。我无法找到验证错误 以下是我的数据库架构: 以下是我的看法: @model globalEngineProject.make @{ ViewBag.Title = "Index"; } <h2>Index</h2> @using (Html.BeginForm("Home", "make", FormMethod.Post,

我是MVC新手。我在检查所有数据库字段时发现验证错误,但在那里没有发现任何问题,并且仍然收到一个或多个实体验证失败的错误。我无法找到验证错误

以下是我的数据库架构:

以下是我的看法:

@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);
        }
@model globalEngineProject.make
@{
ViewBag.Title=“Index”;
}
指数
@使用(Html.BeginForm(“Home”、“make”、FormMethod.Post、,
新的{enctype=“multipart/form data”})
{
@Html.AntiForgeryToken()
类别

@Html.ValidationSummary(true) @LabelFor(model=>model.title,新的{@class=“controllabel col-md-2”}) @EditorFor(model=>model.title) @Html.ValidationMessageFor(model=>model.title) @LabelFor(model=>model.category_id,“category_id”,新的{@class=“control label col-md-2”}) @Html.DropDownList(“category_id”,String.Empty) @Html.ValidationMessageFor(model=>model.category\u id) @LabelFor(model=>model.imagePath,新的{@class=“controllabel col-md-2”}) @Html.ValidationMessageFor(model=>model.imagePath) } [HttpPost] [ValidateAntiForgeryToken] 公共操作结果主页([Bind(Include=“make\u id,category\u id,title”)]make-make,HttpPostedFileBase文件) { 尝试 { if(ModelState.IsValid) { 如果(file!=null&&file.ContentLength>0) { var fileName=Path.GetFileName(file.fileName); var path=path.Combine(Server.MapPath(“~/images/”),文件名); file.SaveAs(路径); } db.make.Add(make); db.SaveChanges(); } ViewBag.category\u id=新选择列表(db.categories,“category\u id”,“category\u name”,make.category\u id); 返回视图(make); //返回视图(“索引”); } 捕获(RetryLimitExceedexception) { //记录错误(取消注释dex变量名,并在此处添加一行以写入日志)。 ModelState.AddModelError(“,”无法保存更改。请重试,如果问题仍然存在,请与系统管理员联系。“); } 返回视图(make); }
要展开Stephen的评论,您似乎没有设置
imagePath
的值。要检查这一点,您可以在控制器方法中输入以下代码,以了解验证错误的详细信息:

var modelErrors = new List<ModelError>();

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        modelErrors.Add(error);
    }
}
var modelErrors=新列表();
foreach(ViewData.ModelState.Values中的ModelState ModelState){
foreach(modelState.Errors中的ModelError错误){
modelErrors.Add(错误);
}
}

这将为您提供调试时可以检查的
ModelError
列表。这将为您提供一个指向哪个字段有错误的指针。

inspect
ModelState
以确定您有哪些验证错误。另外,请注意,在保存模型之前,您没有设置属性
imagePath
的值ode>imagePath属性没有
[Required]
属性,因此这不太可能是问题所在(除非OP没有显示正确的代码)。当然,您是对的。我假设,因为视图包含
@Html.ValidationMessageFor(model=>model.imagePath)
必须在其他地方对此属性进行验证。当然可能不是这样。我添加了[必需的]属性,但现在我无法保存数据。它显示图像路径字段是必需的。我不确定您是否希望模型上需要
imagePath
,因为您在控制器代码中设置它的方式。您没有将
imagePath
作为模型绑定的一部分传递给控制器-您正在生成它ver sidethanx对于帮助,我没有设置图像路径字段的值,这就是它显示验证错误的原因
var modelErrors = new List<ModelError>();

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        modelErrors.Add(error);
    }
}