如何通过 AJAX post 使用服务器端验证?
Scott Guthrie 在他的博客文章中描述了如何使用 DataAnnotations 启用验证。
示例:
public class Product
{
[Display(Name="Product Number")]
[Range(0, 5000)]
public int ProductID { get; set; }
[Display(Name="Name")]
[Required]
public string ProductName { get; set; }
[Display(Name="Price")]
[DataType(DataType.Currency)]
public double ListPrice { get; set; }
}
在这篇博文的评论中 @Ke 写道:
服务器端验证如何与 ajax post 一起工作?即,我如何将验证错误发送回客户端?
斯科特回复道:
是的 - 你可以处理这个问题。我相信 Phil Haack 很快就会将其列入他的博客列表中。
但我找不到这篇博文。如何将服务器端验证与 AJAX post 结合起来?
我见过的最好的选择似乎涉及使用部分将表单发送回客户端。我宁愿使用客户端 Javascript 来启用错误消息。
In his blog post, Scott Guthrie describes how to enable validation using DataAnnotations.
Example:
public class Product
{
[Display(Name="Product Number")]
[Range(0, 5000)]
public int ProductID { get; set; }
[Display(Name="Name")]
[Required]
public string ProductName { get; set; }
[Display(Name="Price")]
[DataType(DataType.Currency)]
public double ListPrice { get; set; }
}
In the comments to this blog post @Ke wrote:
How do the server side validations work with ajax post? i.e, how can i send the validation errors back to the client?
Scott replied with:
Yes - you can handle this. I believe Phil Haack has it on his list to blog about soon.
I cannot find this blog post though. How do I combine server-side validation with an AJAX post?
The best options I've seen seem to involve using partials to send the form back to the client. I would rather use client-side Javascript to enable the error messages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
数据注释验证的工作方式是将特殊的 css 类应用到包含错误的字段,并且错误消息由生成相应 div 的 html 帮助程序显示。因此,实际上最好的选择是返回包含允许您显示错误消息的表单的部分视图。
如果您想使用
JSON
或XML
,则必须在响应结构中手动传递验证错误,并在成功回调中使用 javascript 手动处理它。就客户端验证而言,它会起作用,因为如果验证失败,则不会提交表单(无论是否使用ajax)。
The way data annotation validation works is by applying special css classes to the fields containing errors and error messages are shown by html helpers that generate the corresponding divs. So indeed the best option would be to return a partial view containing the form allowing you to show the error messages.
If you want to use
JSON
orXML
instead you will have to pass the validation errors manually in the response structure and handle it manually using javascript in the success callback.As far as client-side validation is concerned, it will work because the form won't be submitted (using ajax or not) if validation fails.