Tengo un formulario para persistir datos con entity framework
, le pongo DataAnnotations
a mi modelo, pero aún así no me validan los valores, no me aparecen los mensajes de error, si no pongo nada en el campo nombre o en el select
de género, al guardar, me arroja una excepción:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.`. Que está pasando?
Modelo:
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
}
}
Controlador:
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" />
}