7

我现在正在试验不同的客户端 MVC 框架(主要是 Backbone 和 Knockout)。我正在尝试提出一种验证方法。我有只返回数据的 MVC 4 Web API。所有视图引擎逻辑都在客户端。显然,我知道服务器端验证是必须的。这一点,我通过模型绑定使用 DataAnnotations 和标准 ASP.NET MVC 验证来实现。

但是,我最终在客户端也复制了所有验证逻辑。有没有办法返回数据但附加了验证逻辑?

4

2 回答 2

5

Blast-Dan is partially right, meaning that you cannot pass extra data to your server from the client aside from Key-Value pairs.

What you can do, however, is propagate your DataAnnotations to the client so that some validation code does not need to be rewritten. It is not trivial for complex rules, but the Html.EditorFor helpers will help you generate text boxes for input with attached validation attributes that are picked up seamlessly by jquery validation and stop the form submitting. I am thinking about [Required], [Range()] and [RegularExpression()] Data Annotations to name a few.

You can see a quick example if you just create a normal model and then add the Controller in Visual Studio using the wizard to create the Views for CRUD operations. You will see how the Data Annotations you used in the Model class end up being rendered on the output html.

If you are creating the HTML yourself without HtmlHelper (which I think you may be doin given the knockout tag) you may want to check the DataAnnotationsModelValidatorProvider and the IClientValidatable interface starting from this link.

As you can see, this is still uncharted territory tho :/

于 2012-05-26T03:08:16.100 回答
2

不,

向服务器提供数据时,您需要使用 HTTP 协议,您将使用 Post 或 Get 方法。这只能传递键值对。使用 MVC 数据绑定,您可以绑定这些键值对来创建复杂对象。

但是,无法将元数据或函数传输到 C# 以完成验证。所有验证逻辑都需要在服务器端和客户端脚本语言上编写,以提供正确的验证

于 2012-05-25T19:58:11.110 回答