Asp MVC 模型实体验证不显示必需的错误 [英] Asp MVC Model Entity Validation does not displaying Required Error

查看:57
本文介绍了Asp MVC 模型实体验证不显示必需的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过模型实体必需属性验证表单.我在 Db 模型类中声明了必需的属性,但是当字段保持为空时无法查看验证错误,但是如果表单字段不为空,则将数据插入到 Db 中,但当它们为空时不会发生验证错误.

这是我的模型类代码:

命名空间 MVCLogin.Models{使用系统;使用 System.Collections.Generic;使用 System.ComponentModel;使用 System.ComponentModel.DataAnnotations;公共部分类 EmployeeTbl{公共 int ID { 获取;放;}public Nullable部门 ID { 获取;放;}[Required(ErrorMessage = "Name is required. ")]公共字符串名称 { 获取;放;}公共字符串薪水{得到;放;}[Required(ErrorMessage = "需要联系方式.")]公共字符串联系{获取;放;}[Required(ErrorMessage = "电子邮件是必需的.")][数据类型(数据类型.电子邮件地址)]公共字符串电子邮件{获取;放;}公共字符串处{get;放;}公共虚拟部门部门{获取;放;}

这是我的控制器代码:

命名空间MVCLogin.Controllers{公共类 EmpController : 控制器{公共 ActionResult SaveRecord(){返回视图();}[HttpPost]公共 ActionResult SaveRecord(EmployeeTbl 模型,FormCollection 表单){尝试{LoginDatabaseEntities3 db = new LoginDatabaseEntities3();EmployeeTbl emp = new EmployeeTbl();emp.Name = 模型.Name;emp.Salary = 模型.Salary;emp.Contact = model.Contact;emp.Email = 模型.Email;string strDepartment = form["departmentlist1"].ToString();emp.Department = strDepartment;emp.DeptID = 模型.DeptID;db.EmployeeTbls.Add(emp);db.SaveChanges();int latestEmpId = emp.ID;}捕获(异常前){扔前;}return RedirectToAction("viewemployeeDetails", "EmpDetails");}公共 ActionResult AddNewEmployee(){LoginDatabaseEntities3 db = new LoginDatabaseEntities3();var getdepartmentlist = db.Depts.ToList();SelectList list = new SelectList(getdepartmentlist, "Name", "Name");ViewBag.departmentlistname = list;返回视图();}

这是我的查看代码:

@model MVCLogin.Models.EmployeeTbl@{ViewBag.Title = "添加员工";布局 = 空;}<!DOCTYPE html><头><meta name="viewport" content="width=device-width"/><title>AddNewEmployee</title><style type="text/css">#EmpAdd{填充左:500px;填充顶部:2px;}#Home-Link {padding-left: 5px;填充:10px 10px;}.field-validation-error{红色;}</风格><link href="~/Content/bootstrap.css" rel="stylesheet"/><script src="~/Scripts/all.js"></script><script src="~/Scripts/jquery-3.0.0.min.js"></script><script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script><script src="~/Scripts/jquery.validate.js"></script><script src="~/Scripts/jquery.validate.min.js"></script><身体><div id="EmpAdd">@using (Html.BeginForm("AddNewEmployee", "Emp", FormMethod.Post)){@Html.ValidationSummary(true)<字段集><legend>员工详情</legend><div class="editor-label">@Html.LabelFor(model => model.Name)

<div class="editor-field">@Html.EditorFor(model => model.Name)

<div class="editor-label">@Html.LabelFor(model => model.Salary)

<div class="editor-field">@Html.EditorFor(model => model.Salary)

<div class="editor-label">@Html.LabelFor(model => model.Contact)

<div class="editor-field">@Html.EditorFor(model => model.Contact)@Html.ValidationMessageFor(model => model.Contact)

<div class="editor-label">@Html.LabelFor(model => model.Email)

<div class="editor-field">@Html.EditorFor(model => model.Email)@Html.ValidationMessageFor(model => model.Email)

<div class="editor-label">@Html.LabelFor(model => model.Department)

<div class="editor-field">@Html.DropDownList("departmentlist1", ViewBag.departmentlistname as SelectList, "请选择部门")

<div style="position:center;"><p><input type="submit" value="Save Record" class="btn btn-success"/></p>

</fieldset>}

<div id="Home-Link">@if (Session.SessionID == Session.SessionID){@Html.ActionLink("返回首页", "仪表板", "首页")}

<div id="Render-Section">@RenderPage("~/Views/Shared/_Layout.cshtml")

</html>

解决方案

终于找到了我的问题的答案,我必须在我的 POST 操作中重新填充下拉列表.

公共类 EmpController : 控制器{公共 ActionResult AddNewEmployee(){LoginDatabaseEntities3 db = new LoginDatabaseEntities3();var getdepartmentlist = db.Depts.ToList();SelectList list = new SelectList(getdepartmentlist, "ID", "Name");ViewBag.departmentlistname = list;返回视图();}[HttpPost]公共 ActionResult AddNewEmployee(EmployeeTbl 模型){LoginDatabaseEntities3 db = new LoginDatabaseEntities3();var getdepartmentlist = db.Depts.ToList();SelectList list = new SelectList(getdepartmentlist, "ID", "Name");ViewBag.departmentlistname = list;if(!ModelState.IsValid){返回视图(模型);}db.EmployeeTbls.Add(model);db.SaveChanges();int latestEmpId = model.ID;return RedirectToAction("viewemployeeDetails", "EmpDetails");}}

甚至字段验证也能正常工作.

I want to validate a form via Model Entity Required Attribute. I have Declared Required Attribute in Db Model Class, but not able to view the validation error when the filed remains empty, However the data is inserted into Db if the form fields are not empty but when they are empty no Validation Error occurs.

Here is my Model Class Code:

namespace MVCLogin.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;

    public partial class EmployeeTbl
    {
        public int ID { get; set; }
        public Nullable<int> DeptID { get; set; }

        [Required(ErrorMessage = "Name is required. ")]
        public string Name { get; set; }
        public string Salary { get; set; }

        [Required(ErrorMessage = "Contact is required. ")]
        public string Contact { get; set; }

        [Required(ErrorMessage = "Email is required. ")]
        [DataType(DataType.EmailAddress)]
        public string Email { get; set; }


        public string Department { get; set; }

        public virtual Dept Dept { get; set; }

Here Is my Controller Code:

namespace MVCLogin.Controllers
{
    public class EmpController : Controller
    {
        public ActionResult SaveRecord()
        {
            return View();
        }


        [HttpPost]
        public ActionResult SaveRecord(EmployeeTbl model, FormCollection form)
        {

            try
            {
                LoginDatabaseEntities3 db = new LoginDatabaseEntities3();
                EmployeeTbl emp = new EmployeeTbl();
                emp.Name = model.Name;
                emp.Salary = model.Salary;
                emp.Contact = model.Contact;
                emp.Email = model.Email;
                string strDepartment = form["departmentlist1"].ToString();
                emp.Department = strDepartment;
                emp.DeptID = model.DeptID;
                db.EmployeeTbls.Add(emp);
                db.SaveChanges();
                int latestEmpId = emp.ID;           
            }

            catch (Exception ex)
            {
                throw ex;
            }

            return RedirectToAction("viewemployeeDetails", "EmpDetails");

        }



        public ActionResult AddNewEmployee()
        {
            LoginDatabaseEntities3 db = new LoginDatabaseEntities3();
            var getdepartmentlist = db.Depts.ToList();
            SelectList list = new SelectList(getdepartmentlist, "Name", "Name");
            ViewBag.departmentlistname = list;
            return View();

        }

And here is my View Code:

@model MVCLogin.Models.EmployeeTbl
@{
    ViewBag.Title = "Add Employee";
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddNewEmployee</title>
    <style type="text/css">
        #EmpAdd{
            padding-left :500px;
            padding-top:2px;
        }
        #Home-Link {
            padding-left: 5px;
            padding: 10px 10px;
        }
        .field-validation-error{
            color:red;
        }
    </style>
    <link href="~/Content/bootstrap.css" rel="stylesheet" />
    <script src="~/Scripts/all.js"></script>
    <script src="~/Scripts/jquery-3.0.0.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
    <script src="~/Scripts/jquery.validate.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
</head>
<body>
    <div id="EmpAdd">

        @using (Html.BeginForm("AddNewEmployee", "Emp", FormMethod.Post))
        {

            @Html.ValidationSummary(true)
            <fieldset>

                <legend>Employee Details</legend>
                <div class="editor-label">
                    @Html.LabelFor(model => model.Name)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.Name)

                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.Salary)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.Salary)

                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.Contact)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.Contact)
                    @Html.ValidationMessageFor(model => model.Contact)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.Email)
                </div>
                <div class="editor-field">
                    @Html.EditorFor(model => model.Email)
                    @Html.ValidationMessageFor(model => model.Email)
                </div>

                <div class="editor-label">
                    @Html.LabelFor(model => model.Department)
                </div>
                <div class="editor-field">
                    @Html.DropDownList("departmentlist1", ViewBag.departmentlistname as SelectList, "Please Select Department")

                </div>
                <div style="position:center;">
                    <p>
                        <input type="submit" value="Save Record" class="btn btn-success" />
                    </p>
                </div>

            </fieldset>
        }
    </div>



    <div id="Home-Link">
        @if (Session.SessionID == Session.SessionID)
        {
            @Html.ActionLink("Back to Home", "Dashboard", "Home")
        }

    </div>

    <div id="Render-Section">
        @RenderPage("~/Views/Shared/_Layout.cshtml")
    </div>

</body>
</html>

解决方案

Finally found the answer of my problem, i have to repopulate the DropDown list in my POST Action.

public class EmpController : Controller
{
     public ActionResult AddNewEmployee()
     {
         LoginDatabaseEntities3 db = new LoginDatabaseEntities3();
         var getdepartmentlist = db.Depts.ToList();
         SelectList list = new SelectList(getdepartmentlist, "ID", "Name");
         ViewBag.departmentlistname = list;

         return View();
     }

     [HttpPost]
     public ActionResult AddNewEmployee(EmployeeTbl model)
     {
         LoginDatabaseEntities3 db = new LoginDatabaseEntities3();
         var getdepartmentlist = db.Depts.ToList();
         SelectList list = new SelectList(getdepartmentlist, "ID", "Name");
         ViewBag.departmentlistname = list;

         if(!ModelState.IsValid)
         {
            return View(model);
         } 



         db.EmployeeTbls.Add(model);

         db.SaveChanges();

         int latestEmpId = model.ID;

         return RedirectToAction("viewemployeeDetails", "EmpDetails");
     }

}

And even Fields Validation is working fine.

这篇关于Asp MVC 模型实体验证不显示必需的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆