asp.net-mvc-3 - 将错误消息添加到 @Html.ValidationSummary

标签 asp.net-mvc-3 unobtrusive-validation

我正在使用标准 MVC3 Razor View 和不显眼的 Javascript 验证,使用 @Html.ValidationSummary将它们显示在表单的顶部。如果标准验证(如 [Required] )通过,我然后运行一些非常自定义的客户端验证,当用户点击提交按钮时触发。 (验证会查看多个表单元素以确保它们的正确集合已被检查等,因此它不像只是为单个字段创建一个新的自定义验证器那么简单)。

我希望我在那里构建的可能错误显示在 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"

    }
}

关于asp.net-mvc-3 - 将错误消息添加到 @Html.ValidationSummary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7882008/

相关文章:

asp.net-mvc - 使用 razorgenerator 在不同项目中具有相同名称的 2 个 razor 部分 View

asp.net-mvc-3 - 未提供强制数据时验证错误

c# - 无法将方法组 'ToList' 转换为非委托(delegate)类型

jquery - 从 AJAX 调用附加表单时如何正确设置 MVC 5 不显眼的验证?

asp.net-mvc - ASP.NET MVC [RegularExpression] 属性在整个字符串匹配时不起作用

asp.net-mvc-3 - 创建规范 URL,包括 id 和 title slug

c# - 我的图像不会添加 C#

asp.net-mvc-4 - jQuery 不显眼的验证不起作用

c# - 显示验证成功的消息

jquery - 带有 jQ​​uery 验证的 RequireJS - 设置默认设置