Validations with Data Annotations in the Entity framework do not work

0

I have a form made in Asp.NET MVC using Entity framework for persistence and using Data Annotations to validate the fields. The problem I have is that the validations do not work, I want to put fields with null value, I want to save the fields and I get an exception in line throw new System.Exception(errorMessage); of the controller and when I look at the detail it says:

Entity of type "Estudiante" in state "Added" has the following validation errors:
- Property: "EstudianteNombre", Error: "El campo EstudianteNombre es obligatorio."
- Property: "EstudianteGenero", Error: "El campo EstudianteGenero es obligatorio."

and then I shot the following screen:

Error de servidor en la aplicación '/'.

Entity of type "Estudiante" in state "Added" has the following validation errors:
- Property: "EstudianteNombre", Error: "El campo EstudianteNombre es obligatorio."
- Property: "EstudianteGenero", Error: "El campo EstudianteGenero es obligatorio."
Descripción: Excepción no controlada al ejecutar la solicitud Web actual. Revise el seguimiento de la pila para obtener más información acerca del error y dónde se originó en el código.

Detalles de la excepción: System.Exception:
Entity of type "Estudiante" in state "Added" has the following validation errors:
- Property: "EstudianteNombre", Error: "El campo EstudianteNombre es obligatorio."
- Property: "EstudianteGenero", Error: "El campo EstudianteGenero es obligatorio."

    Error de código fuente:


    Línea 58:                                }
    Línea 59:                            }
    Línea 60:                            throw new System.Exception(errorMessage);
    Línea 61:                        } 
    Línea 62:                     return RedirectToAction("Crear", "Home");

What is happening? I have the lines in my web.config

<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

View:

@model Estudiante
@using (Html.BeginForm())
{
<br />
@Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.EstudianteNombre, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.EstudianteNombre, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.EstudianteNombre, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.EstudianteGenero, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("EstudianteGenero", (IEnumerable<SelectListItem>)ViewData["Genero"], "Select Gender", new { @class = "form-control" })

            @Html.ValidationMessageFor(model => model.EstudianteGenero, "", new { @class = "text-danger" })
        </div>
    </div>
    <br />

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Crear"lass="btn btn-default" />
        </div>
    </div>
}

<script src="~/Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>

Controller:

using Lista7.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Lista7.Controllers
{
    public class HomeController : Controller
    {

        private EstudianteEntities db = new EstudianteEntities();

        // GET: Home
        public ActionResult Crear()
        {
            var estudiante = new Estudiante();

            var items = new List<SelectListItem>
            {
                new SelectListItem {Text = "Masculino", Value = "Masculino"},
                new SelectListItem {Text = "Femenino", Value = "Femenino"},
            };

            ViewData["Genero"] = items;

            return View(estudiante);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Crear([Bind(Include = "EstudianteId,EstudianteNombre,EstudianteGenero")] Estudiante stu)
        {
            if (ModelState.IsValid)
            {

                try
                {
                    db.Estudiante.Add(stu);
                    db.SaveChanges();
                }

                      catch (DbEntityValidationException e)
                       {
                           string errorMessage = "";
                           foreach (var eve in e.EntityValidationErrors)
                           {
                               errorMessage = string.Format("\nEntity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                   eve.Entry.Entity.GetType().Name, eve.Entry.State);
                               foreach (var ve in eve.ValidationErrors)
                               {
                                   errorMessage += string.Format("\n- Property: \"{0}\", Error: \"{1}\"",
                                       ve.PropertyName, ve.ErrorMessage);
                               }
                           }
                           throw new System.Exception(errorMessage);
                       } 
                    return RedirectToAction("Crear", "Home");




            }

            return View(stu);
        }
    }
}

Model

 Estudiante.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using Lista7.Models;

namespace Lista7.Models
{


    [MetadataType(typeof(EstudianteMetaData))]
    public partial class Estudiante
    {
    }


    public enum Genero
    {
        Masculino,
        Femenino
    }
}

StudentMetaData.cs

using Lista7.Models;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;

    namespace Lista7.Models
    {
        public class EstudianteMetaData
        {
            public int EstudianteId { get; set; }
            [Required]
            [StringLength(50)]
            public string EstudianteNombre { get; set; }
            [Required]
            public Genero EstudianteGenero { get; set; }
        }
    }
    
asked by Andrés Oporto 12.06.2017 в 19:01
source

0 answers