DRY Remote Validation in ASP.NET MVC 3

霸气de小男生 提交于 2019-12-09 07:39:27
Adam Tuliper - MSFT

It 'can' be done.. but you would need to write your own custom attribute that basically emits for client side and is validated server side. For me I just extract the validation code into a method and check on the server. Something similar came up recently as well:

Prevent form from submitting when using unobtrusive validation in ASP.NET MVC 3

I wonder if one couldnt inherit from the remote attribute and add their own server side code them. hmm.. maybe I'll have to try this.

I would be happy though if someone here said they already did this : )

See my MSDN article How to: Implement Remote Validation in ASP.NET MVC I use the remote client validation code in the HttpPost Create method to test server side when JavaScript is disabled.

[HttpPost]
    public ActionResult Create(CreateUserModel model) {

        // Verify user name for clients who have JavaScript disabled
        if (_repository.UserExists(model.UserName)) {
            ModelState.AddModelError("UserName", ValidationController.GetAltName(model.UserName, _repository));
            return View("Create", model);
        }

I have done this, it's a bit of a long solution, so it's all available on my blog here:

http://www.metaltheater.com/tech/technical/fixing-the-remote-validation-attribute/

I had to create a new subclass of the RemoteAttribute class, create my own custom model binder by inheriting from DefaultModelBinder, and then use reflection to call the validator on the controller.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!