简体   繁体   English

请参阅控制器中的验证摘要

[英]See the Validation Summary in the controller

I have a strongly-typed ajax call (POST) in one of my MVC pages. 我的一个MVC页面中有一个强类型的ajax调用(POST)。 I don't want to try and wire up client-side validation for that, and there will be no summaries to display on the client side, however, I'd like to throw some data annotations on the model and validate on the controller; 我不想尝试为此进行客户端验证,并且不会在客户端显示摘要,但是,我想在模型上抛出一些数据注释并在控制器上进行验证; if it fails validation I'd like to send back what would have been in the validation summary as a JSON property so I can show it in a dialog box as an error message. 如果验证失败,我想将验证摘要中的内容作为JSON属性发回,这样我就可以在对话框中将其显示为错误消息。

How can I provide the JsonResponse the text of the validation summary in my controller? 如何在控制器中为JsonResponse提供验证摘要的文本?

If you are trying to obtain the errors, you would simply use ModelState.Errors to obtain all of the errors from your controller. 如果您尝试获取错误,则只需使用ModelState.Errors从控制器获取所有错误。 From there you can craft the JSON response any way you'd like: 从那里你可以按照你想要的方式制作JSON响应:

var response = new
                    {
                        isValid = ModelState.IsValid,
                        errors = ModelState
                        .SelectMany(ms => ms.Value.Errors)
                        .Select(ms => ms.ErrorMessage)
                    };
return Json(response);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM