【问题标题】:Validation Using service layer in mvc 4 to achieve server side and client side validation验证 在 mvc 4 中使用服务层实现服务器端和客户端验证
【发布时间】:2014-11-06 10:16:36
【问题描述】:

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

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

  1. 服务层

  2. 员工资料库

员工存储库代码是

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


    }
}

我的观点是这样的

我的问题是上面的代码对于服务器端验证工作正常

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

【问题讨论】:

    标签: c# asp.net-mvc validation


    【解决方案1】:

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

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

    因此,您有三个选择。

    1. 将返回类型更改为 ModelStateDictionary。
    2. 创建新的返回类型以返回结果和 ModelStateDictionary。
    3. 使用模型状态无效时发生的故障异常。

    我个人会使用第三种方法,因为您仍然可以使用原始返回类型,然后只需要像捕获异常一样捕获错误。这是exampleMSDN

    【讨论】:

    • 你能附上一些代码我在哪里返回modelstatedictionary
    • 我的想法是我不想将表单发布到服务器端进行验证我想在不使用 dataannotation 和 jquery 的情况下在客户端获得验证错误
    猜你喜欢
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    相关资源
    最近更新 更多