将字段留空时验证不起作用

时间:2018-12-26 17:59:40

标签: c# asp.net-mvc validation razor

我正在尝试为视图中的字段创建验证,因此,如果用户将其保留为空白,则会在每个字段下方显示一条验证消息。

我的问题是,每次我通过将其中一个字段保留为空来测试验证时,都会出现context.SaveChanges()错误,并且得到此消息

  

一个或多个实体的验证失败。有关更多详细信息,请参见“ EntityValidationErrors”属性,这里的问题出在哪里?

这是我的模特

public class NewsViewModel
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Title is required")]
    public string Title { get; set; }
    [Required(ErrorMessage = "Text is required")]
    public string Text { get; set; }

}

这是我的控制人,

public ActionResult AlterNews(News model )
{
    var context = new BackOfficeEntities();
    if (ModelState.IsValid)
    {

            var update = context.News.SingleOrDefault(x => x.Id == model.Id);

            update.Title = model.Title;
            update.Text = model.Text;
            context.SaveChanges();
            return RedirectToAction("Index", "News");       
    }
    return View(model);
}

最后是视图

@using (Html.BeginForm("AlterNews", "News"))
{
    @Html.AntiForgeryToken()

    @Html.ValidationSummary("", new { @class = "text-danger" })

    <fieldset>
        <div class="col-md-4">
            <div class="form-group">
                @Html.HiddenFor(Model => Model.Id, new { @class = "control-label" })

                @Html.LabelFor(Model => Model.Title)
                @Html.TextBoxFor(Model => Model.Title, new { @class = "form-control" })
                @Html.ValidationMessageFor(Model => Model.Title)
            </div>

            <div class="form-group">


                @Html.LabelFor(Model => Model.Text, new { @class = "control-label" })
                @Html.TextAreaFor(Model => Model.Text, new { @class = "form-control", rows = "10" })
                @Html.ValidationMessageFor(Model => Model.Text)
            </div>
        </div>

    </fieldset>
    <div class="col-md-4">

        <button type="submit" class="btn btn-default" name="buttonSubmit" value="Edit News">Edit News</button>
    </div>
}
@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

1 个答案:

答案 0 :(得分:1)

您可以尝试检查基本的验证错误,这将提示您导致错误的原因。

try{

      var update = context.News.SingleOrDefault(x => x.Id == model.Id);

      update.Title = model.Title;
      update.Text = model.Text;
      context.SaveChanges();

}
catch(DbEntityValidationException ex)
{
        StringBuilder result = new StringBuilder();
        var entityErrors = ex.EntityValidationErrors;

        foreach (var entity in entityErrors)
        {
            foreach (var error in entity.ValidationErrors)
            {
                result.Append(error.PropertyName + " - " + error.ErrorMessage + "\n");
            }
        }        
        throw;
}