Data Annotations in a form do not work

1

I have a form to persist data with entity framework , I put DataAnnotations to my model, but still I do not validate the values, I do not see the messages of error , if I do not put nothing in the name field or in the select of genre, when saving, throws an exception:

  

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.'. What's happening?

Model :

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

namespace Lista.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        [Required]
        [StringLength(10, MinimumLength = 2, ErrorMessage = " El {0} debe tener entre 2 y 10 caracteres")]
        public string StudentName { get; set; }
        [Required(ErrorMessage = " Debe elegir sexo")]      
        public Gender StudentGender { get; set; }
    }

    public enum Gender
    {
        Male,
        Female
    }
}

Driver :

using Lista.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Lista.Controllers
{
    public class HomeController : Controller
    {

        private pruebaEntities db = new pruebaEntities();

        // GET: Home
        public ActionResult Index()
        {
            var sudent = new Student();

            var items = new List<SelectListItem>
    {
        new SelectListItem {Text = "Male", Value = "Male"},
        new SelectListItem {Text = "Female", Value = "Female"},
    };

            ViewData["Genders"] = items;

            return View();
        }


        [HttpPost]
        public ActionResult Index(Student st)
        {
            if (ModelState.IsValid)
            {
                db.Student.Add(st);
                db.SaveChanges();

                return RedirectToAction("Index", "Home");
            }

            return View(st);
        }
    }
}

Vista :

@model Student
@using (Html.BeginForm("CrearCliente"))
{
<br />
    @Html.EditorFor(model => model.StudentName)
    @Html.ValidationMessageFor(m => m.StudentName)
    @Html.DropDownList("StudentGender", (IEnumerable<SelectListItem>)ViewData["Genders"], "Select Gender", new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.StudentGender)
    <input type="submit" value="Guardar" />
}
    
asked by Andrés Oporto 09.06.2017 в 20:20
source

2 answers

1

You can try to build your own html in the following way. Personally I like to build myself the html, I think that in some way I make it easier for the server to have to render all the controls and then show them

<div class="form-group">
    <input type="text" name="StudentName" value="@Model.StudentName">
    @Html.ValidationMessageFor(s => s.StudentName)
</div>

<select name="StudentGender">
    <option value=""></option>
        @foreach (var gender in ViewData["Genders"])
        {
            <option value="@gender.Id">@gender.Name</option>
        }
</select>
@Html.ValidationMessageFor(m => m.ProfesionId)

I hope this example will help you.

    
answered by 24.03.2018 в 16:34
0

It seems that you are missing the JQuery validation.

Make sure you have the following in the view:

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

I imagine you're going to have to change the path.

Or include it in the bundle (if you're using it)

    
answered by 09.06.2017 в 20:31