0

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")
}
Matthijs
  • 2,483
  • 5
  • 22
  • 33
Bader H Al Rayyes
  • 514
  • 2
  • 7
  • 24
  • You have quite a number of issues (not question related). It doesn't appear you are using the [AntiForgeryToken](http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/) to prevent cross site forgery's. Your `label` tags `for` attributes don't point to other HtmlElement Id's (just non-standard). You don't need to [retrieve the object from the database to update it (that's just more overhead)](https://stackoverflow.com/questions/11421370/efficient-way-of-updating-list-of-entities/11421706#11421706). – Erik Philips Dec 26 '18 at 18:23
  • What Validation error messages do you get? – Erik Philips Dec 26 '18 at 18:24
  • Let us know what the error says; catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) – Sgedda Dec 26 '18 at 18:29
  • The error is a validation from the database because I leave the text field empty to make sure that the validation will work on the page, but it does not, that's why I get the error. the error is not important here because It does not say why my validation is not working... – Bader H Al Rayyes Dec 26 '18 at 18:42
  • Is this NewsViewModel used at all? Your controller is accepting public ActionResult AlterNews(News model), they are two different objects – Felix Cen Dec 26 '18 at 19:25
  • @FelixCen No, I changed the controller in the question , also improved the view ( i guess) – Bader H Al Rayyes Dec 26 '18 at 19:40
  • What is the model for the view? and what is the implementation of News.cs? – Felix Cen Dec 26 '18 at 19:43
  • The model of view is @model BackOffice.EFModel.News – Bader H Al Rayyes Dec 26 '18 at 19:44
  • what is the implementation of News.cs? i do not understand this part sorry , i am a begginer, care to explain ? – Bader H Al Rayyes Dec 26 '18 at 19:45
  • Your controller does not accept NewsViewModel but News. public ActionResult AlterNews(News model). So, NewsViewModel and News are two different objects. Can you also, post the entire code of the view? – Felix Cen Dec 26 '18 at 19:46
  • The AlterNews(News model ) News here is the same => model BackOffice.EFModel.News , where did I go wrong ? – Bader H Al Rayyes Dec 26 '18 at 19:48
  • @FelixCen I changed the controller, and removed the NewsViewModel, I do not use it anymore, please check the question again and see the new code for controller . – Bader H Al Rayyes Dec 26 '18 at 19:49
  • I also capable to edit the form and save it normally, my problem here is the validation when I leave one of the form feilds empty. – Bader H Al Rayyes Dec 26 '18 at 19:50
  • @FelixCen I think I understood the issue here, but I can not manage to resolve it, I am making validation on my MVC model using annotations, but when I update, I use my EF model in the view, which why the whole thing does not get validated.. – Bader H Al Rayyes Dec 26 '18 at 20:04
  • Just don't use the EF model in the view, and use the view model. When you return the view model from the GET method you will need to do the same – Felix Cen Dec 26 '18 at 20:12
  • maybe your entity model does not accept null value – ecstatic Dec 27 '18 at 09:37

1 Answers1

1

You can try checking the underlying validation error, that will give you hints what is causing the error.

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;
}
Felix Cen
  • 733
  • 1
  • 6
  • 24
  • How does this answer **solve the question** *My problem is every time I test the validation by leaving one of the fields empty, I get context.SaveChanges() error*? It looks like a step to finding the problem, but it does not at all solve the problem. – Erik Philips Dec 26 '18 at 22:42