实体框架中的数据注释验证不起作用

时间:2017-06-12 18:38:49

标签: asp.net-mvc entity-framework asp.net-mvc-4

我在Asp.NET MVC中使用Entity Framework进行持久化并使用数据注释来验证字段。我遇到的问题是验证不起作用。当用户尝试保存空值时,我想要显示警报。

throw new System.Exception (errorMessage);

在控制器中并查看细节说:

  

状态为“已添加”的“学生”类型的实体具有以下验证错误:
   - 属性:“StudentName”,错误:“StudentNameName字段是必需的。”
   - 属性:“StudentGeneral”,错误:“StudentGeneral字段是必需的。”

发生了什么事?我在web.config

中有这些行
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

控制器:

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

namespace Lista6.Controllers
{
    public class HomeController : Controller
    {

        private StudentEntities db = new StudentEntities();

        // GET: Home
        public ActionResult Create()
        {
            var student = new Student();

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

            ViewData["Genders"] = items;

            return View(student);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "StudentId,StudentName,StudentGender")] Student stu)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    db.Student.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("Create", "Home");
            }

            return View(stu);
        }
    }
}

Student.cs

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

namespace Lista.Models
{
    [MetadataType(typeof(StudentMetaData))]
    public partial class Student
    {
    }

    public enum Gender
    {
        Male,
        Female
    }
}

StudentMetaData.cs

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

namespace Lista6.Models
{
    public class StudentMetaData
    {
        public int StudentId { get; set; }
        [Required]
        [StringLength(50)]
        public string StudentName { get; set; }
        [Required]
        public Gender StudentGender { get; set; }
    }
}

查看

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

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

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

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="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>

0 个答案:

没有答案