在向Angular注册数据库中的现有电子邮件时,如何引发警报错误



所以我的问题是,当我想用我的数据库中的电子邮件注册一名新员工时,我希望Angular检查该电子邮件或员工的Id是否已经存在,然后如果你提交了一封现有的电子邮件或Id以显示错误,它会告诉你"电子邮件已经存在"或"EmployeeId已经存在"。我会在下面发布我的api控制器代码、js文件、BusinessLogicLayer的类文件和html文件,告诉我哪里错了。

EmployeeController.cs

namespace EIS.API.Controllers
{
[EnableCors("*", "*", "*")]
public class EmployeeController : ApiController
{
EmployeeBs employeeObjBs;
public EmployeeController()
{
employeeObjBs = new EmployeeBs();
}
//GET /api/employeee
[ResponseType(typeof(IEnumerable<Employee>))]
public IHttpActionResult Get()
{
return Ok(employeeObjBs.GetALL());
}
//GET /api/employeee/1
[ResponseType(typeof(Employee))]
public IHttpActionResult Get(string id)
{
Employee employee = employeeObjBs.GetByID(id);
if (employee != null)
return Ok(employee);
else
{
return NotFound();
}
}
//POST /api/employeee
[ResponseType(typeof(Employee))]
public IHttpActionResult Post(Employee employee)
{
if (ModelState.IsValid)
{
if (employeeObjBs.Insert(employee))
{
return CreatedAtRoute("DefaultApi", new { id = employee.EmployeeId }, employee);
}
else
{
foreach (var error in employeeObjBs.Errors)
{
ModelState.AddModelError("", error);
}
return BadRequest(ModelState);
}
}
else
{
return BadRequest(ModelState);
}
}
//UPDATE /api/employeee
[ResponseType(typeof(Employee))]
public IHttpActionResult Put(string id, Employee employee)
{
if (ModelState.IsValid)
{
employeeObjBs.Update(employee);
return Ok(employee);
}
else
{
return BadRequest(ModelState);
}
}
//DELETE /api/employeee
public IHttpActionResult Delete(string id)
{
Employee employee = employeeObjBs.GetByID(id);
if (employee != null)
{
employeeObjBs.Delete(id);
return Ok(employee);
}
else
{
return NotFound();
}
}
}
}

EmployeeBs.cs

namespace EIS.BLL
{
public class EmployeeBs
{
private EmployeeDb ObjDb;
public List<string> Errors = new List<string>();
public EmployeeBs()
{
ObjDb = new EmployeeDb();
}
public IEnumerable<Employee> GetALL()
{
return ObjDb.GetALL().ToList();
}
public Employee GetByID(string Id)
{
return ObjDb.GetByID(Id);
}
public bool Insert(Employee emp)
{
if (IsValidOnInsert(emp))
{
ObjDb.Insert(emp);
return true;
}
else
{
return false;
}
}
public void Delete(string Id)
{
ObjDb.Delete(Id);
}
public bool Update(Employee emp)
{
if (IsValidOnUpdate(emp))
{
ObjDb.Update(emp);
return true;
}
else
{
return false;
}
}
public Employee GetByEmail(string email)
{
return ObjDb.GetByEmail(email);
}
public Employee RecoverPasswordByEmail(string email)
{
var emp = ObjDb.GetByEmail(email);
return emp;
}
public bool IsValidOnInsert(Employee emp)
{
//Unique Employee Id Validation
string EmployeeIdValue = emp.EmployeeId;
int count = GetALL().Where(x => x.EmployeeId == EmployeeIdValue).ToList().Count();
if (count != 0)
{
Errors.Add("Employee Id Already Exist");
}
//Unique Email Validation
string EmailValue = emp.Email;
count = GetALL().Where(x => x.Email == EmailValue).ToList().Count();
if (count != 0)
{
Errors.Add("Email Already Exist");
}
//Your own Business Rules Validations
if (Errors.Count() == 0)
return true;
else
return false;
}
public bool IsValidOnUpdate(Employee emp)
{
return true;
}
}
}

EmployeeMgmt.html

<div id="alert" class="alert alert-success" ng-show="Flg">
{{message}}

<form name="createEmployeeForm" novalidate>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Create Employee Profile</h3>
</div>
</div>
<div class="panel-body">
<div class="panel-body">
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2">Employee Id *</label>
<div class="col-md-4">
<input type="text" class="form-control" ng-model="Emp.EmployeeId" name="EmployeeId" value="EmployeeId" required/>
</div>

</div>
<div class="form-group">
<label class="control-label col-md-2">Email *</label>
<div class="col-md-4">
<input type="email" class="form-control" ng-model="Emp.Email" name="Email" value="Email" required/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-6">
<button type="submit" value="Create" ng-click="CreateEmployee(Emp,createEmployeeForm.$valid )" class="btn btn-primary btn-lg">Create</button>
</div>
</div>
</div>
<div>
<ul>
<li class="alert alert-danger" ng-if="createEmployeeForm.$submitted && createEmployeeForm.EmployeeId.$invalid">EmployeeId is required</li>
<li class="alert alert-danger" ng-if="createEmployeeForm.$submitted && createEmployeeForm.Email.$error.required">Email is required</li>
<li class="alert alert-danger" ng-if="createEmployeeForm.$submitted && createEmployeeForm.Email.$error.email">Email is Invalid</li>
</ul>
<ul>
<li class="alert alert-danger" ng-repeat="item in serverErrorMsgs">{{item[0]}}</li>
</ul>
</div>
</div>
</div>
</form>
<div class="well">
<input type="text" class="form-control" ng-model="search" placeholder="Type in to search employee" />
</div>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Profiles List - {{msg}}</h3>
</div>
<div class="panel-body">
<table class="table table-striped table-hover">
<thead>
<tr>
<td ng-click="Sort('EmployeeId')"><a><u>EmployeeId</u></a></td>
<td ng-click="Sort('Email')"><a><u>Email</u></a></td>
<td ng-click="Sort('FirstName')"><a><u>Name</u></a></td>
<td ng-click="Sort('Contact')"><a><u>Contact</u></a></td>
</tr>
</thead>
<tbody>
<tr dir-paginate="emp in Emps | filter: search | orderBy: key: AscOrDesc |itemsPerPage:10 ">
<td>{{emp.EmployeeId}}</td>
<td>{{emp.Email}}</td>
<td>{{emp.FirstName}} {{emp.LastName}}</td>
<td>{{emp.Contact}}</td>
</tr>
</tbody>
</table>
<dir-pagination-controls max-size="3"
direction-links="true"
boundary-links="true">
</dir-pagination-controls>
</div>
</div>

employeeMgmt.js

appEIS.factory("employeeMgmtService",
function ($http) {
var empMgmtObj = {};
empMgmtObj.getAll = function () {
var Emps = $http({ method: "Get", url: "http://localhost:53431/api/employee" }); (function (response) {
return response.data;
});
return Emps;
};
empMgmtObj.CreateEmployee = function (emp) {
var Emp = $http({ method: "Post", url: "http://localhost:53431/api/employee", data: emp }); (function (response) {
return response.data;
}, function (error) {
return error.data;
});
return Emp;
};
return empMgmtObj;
});
appEIS.controller("employeeMgmtController", function ($scope, employeeMgmtService, utilityService) {
$scope.msg = "Manage Employee Profiles.";
employeeMgmtService.getAll().then(function (result) {
$scope.Emps = result.data;
});
$scope.Sort = function (col) {
$scope.key = col;
$scope.AscOrDesc = !$scope.AscOrDesc;
};
$scope.CreateEmployee = function(Emp, IsValid) {
if (IsValid) {
Emp.Password = utilityService.randomPassword();
employeeMgmtService.CreateEmployee(Emp).then(function(result) {
if (result.ModelState == null) {
$scope.message = "You have successfully created an Employee with Id: " + result.data.EmployeeId;
$scope.Flg = true;
employeeMgmtService.getAll().then(function(result) {
$scope.Emps = result.data;
});
utilityService.myAlert();
} else {
$scope.serverErrorMsgs = result.ModelState;
}
});
}
};
});

员工.cs

namespace EIS.BOL
{
[Table("Employee")]
public partial class Employee
{
public Employee()
{
CreatedDate = DateTime.Now;
RoleId = 2;
}   
[Key]
[Column(TypeName = "varchar")]
[StringLength(50)]
public string EmployeeId { get; set; }
[Column(TypeName = "varchar")]
[StringLength(50)]
[Required]
public string Email { get; set; }

[Column(TypeName = "varchar")]
[StringLength(50)]
[Required]
public string Password { get; set; }
[NotMapped]
public string ConfirmPassword { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string Contact { get; set; }
public string Address { get; set; }
public DateTime? DOJ { get; set; }
public string Designation { get; set; }
public double? TotalExp { get; set; }
public double? RelevantExp { get; set; }
public string BankName { get; set; }
public string IFSCCode { get; set; }
public string AcNo { get; set; }
public string Pan { get; set; }
public int RoleId { get; set; }
public DateTime CreatedDate { get; set; }
[ForeignKey("RoleId")]
public virtual Role Role { get; set; }
}
}

EmployeeDb.cs

namespace EIS.DAL
{
public class EmployeeDb:DALBase
{
public IEnumerable<Employee> GetALL()
{
return db.Employees.ToList();
}
public Employee GetByID(string Id)
{
return db.Employees.Find(Id);
}
public void Insert(Employee emp)
{
db.Employees.Add(emp);
Save();
}
public void Delete(string Id)
{
Employee emp = db.Employees.Find(Id);
db.Employees.Remove(emp);
Save();
}
public void Update(Employee emp)
{
db.Entry(emp).State = EntityState.Modified;
db.Configuration.ValidateOnSaveEnabled = false;
Save();
db.Configuration.ValidateOnSaveEnabled = true;
}
public Employee GetByEmail(string email)
{
return db.Employees.FirstOrDefault(x => x.Email == email);
}
public void Save()
{
db.SaveChanges();
}
}
}

因此,我想在serverErrorMsgs中显示错误,它来自您在POST方法的控制器中看到的Modelstate。我已经在类文件中列出了错误列表,但当我提交时,它既不做任何事情,也不显示错误。

数据库管理系统将处理重复列错误。

UNIQUE约束。如果将UNIQUE约束添加到具有重复值的列,则数据库引擎将返回错误,并且不添加该约束。数据库引擎自动创建UNIQUE索引,以强制执行UNIQUE约束的唯一性要求。

您可以注册一个监听器来处理来自数据库引擎的"唯一错误"并输出自定义信息。

  1. 更新指定的数据库列以添加唯一约束
  2. 在表中插入重复的值并记录错误信息
  3. 根据错误信息,通过编写try-catch子句来捕获它。用"抓"这个短语做你想做的事

您的异常有3次机会发生:

  1. 插入数据库的值,即使它是重复的值
  2. 错误确实发生了,但没有正确捕获
  3. 错误已成功捕获,但数据未发送到html页面

希望得到帮助。

最新更新