验证在MVC 4使用服务层来实现服务器端和客户端验证

验证在MVC 4使用服务层来实现服务器端和客户端验证

问题描述:

您好我有一些字段的表员工

Hi I have table employee with some fields

要验证我已经创建了两层领域

to validate fields I have created two layers


  1. 服务层

  1. Service layer

员工信息库

员工信息库code是

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;
        }

和我已经创建了两个类来添加验证消息

and I have created two more classes to add validation messages

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
    }

终于员工控制器包含以下结构

finally employee controllers contains below structure

  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");
        }


    }
}

和我的看法是这样的。

我的问题是上面code工作罚款服务器端验证

My question is above code working fine for server side validation

但我怎么使用上面相同的code ++实现对客户端验证

but how do I achieve validation on client side using above same code please

既然你已经在服务端验证,你可以返回ModelStateDictionary而不是布尔的,然后你可以检查它是否在客户端有效。
但是,当涉及到检查整个服务方法结束这不会帮助,所以你可以创建一个新的类型,它返回说布尔和ModelStateDictionary。

Since you are already validating on the service side you could return the ModelStateDictionary instead of the bool, you could then check that it is valid on the client side. But this won't help when it comes to checking that the whole service method has finished, so you could create a new type that returns say a bool and the ModelStateDictionary.

另一种方法是使用故障异常。您可以创建当模型状态无效,将抛出自己的错误异常。这个模型状态故障可能包含你的ModelStateDictionary。

Another approach is to use Fault Exceptions. You can create your own fault exception that would get thrown when the model state is not valid. This Model State Fault could contain your ModelStateDictionary.

所以从你有三个选择。


  1. 更改返回类型为ModelStateDictionary。

  2. 创建一个新的返回类型返回结果和ModelStateDictionary。

  3. 当模型的状态是无效的发生
  4. 使用故障异常。

我个人会用第三种方法,因为,则仍可使用原来的返回类型,然后只需要抓住故障,就像您一个例外。下面是一个例如 MSDN

Personally I would use the third approach, as you can then still use your original return type, and then just need to catch the Fault like you would an Exception. Here is an example and also MSDN