问题
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>
回答1:
You have to call ModelState.IsValid
before u do your work.
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)
{
if(!ModelState.IsValid)
{
return View(model);
}
LoginDatabaseEntities3 db = new LoginDatabaseEntities3();
db.EmployeeTbls.Add(model);
db.SaveChanges();
int latestEmpId = model.ID;
return RedirectToAction("viewemployeeDetails", "EmpDetails");
}
}
Create a view with the name AddNewEmployee.cshtml
@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.DropDownListFor(m => m.DeptID, 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>
</body>
</html>
回答2:
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.
来源:https://stackoverflow.com/questions/51551547/asp-mvc-model-entity-validation-does-not-displaying-required-error