asp.net-mvc-3 – 向@ Html.ValidationSummary添加错误消息

我使用标准的MVC3 Razor视图与不引人注目的Javascript验证,使用@ Html.ValidationSummary来显示它们在表单的顶部。如果标准验证(例如[必需])通过,那么我将在用户点击Submit按钮时运行一些非常自定义的客户端验证。 (验证会查看许多表单元素,以确保其正确的一组已经被检查等等,因此它不像为单个字段创建新的自定义验证器那么简单)。

我想要构建那里的可能的错误显示在ValidationSummary列表中,但是我不知道如何让错误信息出现在那里。

解决方法

在客户端:
function YourCustomValidator() {
    // do your validation logic here via JavaScript
    return true; // or false based on your validation logic
}
$(document).ready(function () {
    // take your own form-selector like ("form",this)
    $("form",this).first().submit(function () {
        return (YourCustomValidator() && $(this).valid());
    });
});

或在服务器端:

认为你有这样的模型:

public class Test {
    [required]
    [StringLength(100)]
    public string FullName { get; set; }
}

当您验证它时:

if(ModelState.IsValid) { // default validations run here
    if(/* some custom validations run here,there is an error about "FullName" */){
        // you should set the "key" for Model-Error to "FullName"
        ModelState.AddModelError("FullName","error-message goes here")
    }
    if(/* some custom validations run here,the error is global,not on "FullName" */){
        // you should set the "key" for Model-Error to an empty-string
        ModelState.AddModelError("","error-message goes here")
    }
    // also you can test for model-errors again like this:
    if(ModelState.IsValid) { // if you add any error above,this will be "false"

    }
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....