验证使用mvc 4中的服务层来实现服务器端和客户端验证

时间:2014-11-06 10:16:37

标签: c# asp.net-mvc validation

您好我有一些表格员工

验证我创建了两个图层的字段

  1. 服务层

  2. 员工资料库

  3. 员工存储库代码

    namespace MvcApplication2.Models
    {
    
        public interface IEmployeeMainTableRepository
        {
            bool CreateEmployee(EMP_MAIN_TBL EmployeeToCreate);
            IEnumerable<EMP_MAIN_TBL> ListEmployees();
        }
    
    
        public class EmployeeRepository : MvcApplication2.Models.IEmployeeMainTableRepository
        {
            private EMPLOYEE_SYSTEMEntities _entities = new EMPLOYEE_SYSTEMEntities();
    
    
            public IEnumerable<EMP_MAIN_TBL> ListEmployees()
            {
                return _entities.EMP_MAIN_TBL.ToList();
            }
    
    
            public bool CreateEmployee(EMP_MAIN_TBL EmployeeToCreate)
            {
                try
                {
                  // _entities.AddToEMP_MAIN_TBL(productToCreate);
                    _entities.SaveChanges();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
    
    
        }
    

    服务层包含

        public interface IEmployeeService
    
        {
            bool CreateEmployee(EMP_MAIN_TBL EmployeeToCreate);
            System.Collections.Generic.IEnumerable<EMP_MAIN_TBL> ListEmployees();
        }
    
        public class EmployeeService : MvcApplication2.Models.IEmployeeService
        {
    
    
            private IValidationDictionary _validatonDictionary;
            private IEmployeeMainTableRepository _repository;
    
            public EmployeeService(IValidationDictionary validationDictionary, IEmployeeMainTableRepository repository)
            {
                _validatonDictionary = validationDictionary;
                _repository = repository;
            }
    
    
    
            protected bool ValidateEmployee(EMP_MAIN_TBL employeeToValidate)
            {
                if (employeeToValidate.EMP_NM == null)
                    _validatonDictionary.AddError("EMP_NM", "Name is required.");
                if (employeeToValidate.PLCE_OF_BRTH == null)
                    _validatonDictionary.AddError("PLCE_OF_BRTH", "Place of birth is required.");
    
                return _validatonDictionary.IsValid;
            }
    
            public IEnumerable<EMP_MAIN_TBL> ListEmployees()
            {
                return _repository.ListEmployees();
            }
    
            public bool CreateEmployee(EMP_MAIN_TBL EmployeeToCreate)
            {
                // Validation logic
                if (!ValidateEmployee(EmployeeToCreate))
                    return false;
    
                // Database logic
                try
                {
                    _repository.CreateEmployee(EmployeeToCreate);
                }
                catch
                {
                    return false;
                }
                return true;
            }
    

    我创建了另外两个类来添加验证消息

    public interface IValidationDictionary
    {
        void AddError(string key, string errorMessage);
        bool IsValid { get; }
    }
    

    public class ModelStateWrapper : IValidationDictionary
        {
    
            private ModelStateDictionary _modelState;
    
            public ModelStateWrapper(ModelStateDictionary modelState)
            {
                _modelState = modelState;
            }
    
            #region IValidationDictionary Members
    
            public void AddError(string key, string errorMessage)
            {
                _modelState.AddModelError(key, errorMessage);
            }
    
            public bool IsValid
            {
                get { return _modelState.IsValid; }
            }
    
            #endregion
        }
    

    最后员工控制器包含以下结构

      public class EmployeeController : Controller
        {
            private IEmployeeService _service;
    
            public EmployeeController()
            {
                _service = new EmployeeService(new ModelStateWrapper(this.ModelState), new EmployeeRepository());
            }
    
            public EmployeeController(IEmployeeService service)
            {
                _service = service;
            }
    
    
            public ActionResult Index()
            {
                return View(_service.ListEmployees());
            }
    
    
            //
            // GET: /Product/Create
    
            public ActionResult Create()
            {
                return View(new EMP_MAIN_TBL());
            }
    
            //
            // POST: /Product/Create
    
            [AcceptVerbs(HttpVerbs.Post)]
            [HttpPost]
            public ActionResult Create([Bind(Exclude = "EMP_ID")] EMP_MAIN_TBL employeeToCreate)
            {
                if (!_service.CreateEmployee(employeeToCreate))
                    return View();
                return RedirectToAction("Index");
            }
    
    
        }
    }
    

    我的观点看起来像这样

    enter image description here

    我的问题是上面的代码适用于服务器端验证

    但是如何使用相同的代码在客户端实现验证 请

1 个答案:

答案 0 :(得分:1)

由于您已经在服务端验证,您可以返回ModelStateDictionary而不是bool,然后您可以检查它在客户端是否有效。 但是,当检查整个服务方法已经完成时,这无济于事,因此您可以创建一个返回bool和ModelStateDictionary的新类型。

另一种方法是使用Fault Exceptions。您可以创建自己的错误异常,当模型状态无效时会抛出异常。此模型状态错误可能包含您的ModelStateDictionary。

因此,你有三个选择。

  1. 将返回类型更改为ModelStateDictionary。
  2. 创建一个新的返回类型以返回结果和ModelStateDictionary。
  3. 使用模型状态无效时发生的故障异常。
  4. 我个人会使用第三种方法,因为你仍然可以使用原始的返回类型,然后只需要像异常一样捕获错误。这是exampleMSDN