I am trying to create validation for my fields in the view, so if the user leaves them blank, a validation message appears under each field.
My problem is every time I test the validation by leaving one of the fields empty, I get context.SaveChanges()
error, and I get this message
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details, where is the issue here?
Here is my model
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; }
}
Here is my controller,
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);
}
And finally, the view
@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")
}