1

我已经阅读了 David Hayden 关于MVC 3 Remote validation的精彩帖子。

但是,这里介绍了启用远程 (javascript) 验证应采取的措施。如果用户禁用了 javascript,即使数据无效,仍然会发布帖子。因此,应该进行服务器端验证。

我们怎样才能使这个检查尽可能 DRY(不要重复自己)?当然,在 post 操作中包含与远程验证操作(或只是相同的调用)相同的检查代码可以工作,但我想知道是否可以使用单行或更优雅的东西。

完全可以接受的答案包括“不,做不到”。:)

4

3 回答 3

4

请参阅我的 MSDN 文章How to:Implement Remote Validation in ASP.NET MVC 我使用 HttpPost Create 方法中的远程客户端验证代码在禁用 JavaScript 时测试服务器端。

[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);
        }
于 2011-05-06T23:05:57.323 回答
2

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 : )

于 2011-04-23T23:57:51.377 回答
1

我已经这样做了,这是一个有点长的解决方案,所以它都可以在我的博客上找到:

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

我必须创建该类的新子RemoteAttribute类,通过继承来创建自己的自定义模型绑定DefaultModelBinder器,然后使用反射调用控制器上的验证器。

于 2013-03-18T06:02:34.523 回答