首页 > 解决方案 > 使用 Angular 在数据库中注册现有电子邮件时如何引发警报错误?

问题描述

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

员工控制器.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>

员工管理.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; }
}
}

员工数据库

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。我已经为类文件中的错误列出了一个列表,但是当我提交它时,它什么也不做,也不显示错误。

标签: angularjsasp.net-mvcvalidationserver-side-validation

解决方案


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

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

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

  1. 更新指定的数据库列以添加唯一约束。
  2. 将重复值插入表中并记录错误信息。
  3. 根据报错信息,通过编码try-catch子句进行捕获。在“catch”短语中做你想做的事。

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

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

希望有所帮助。


推荐阅读