将错误消息添加到@ Html.ValidationSummary

时间:2011-10-24 21:10:02

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

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

我希望我在ValidationSummary列表中显示可能出现的错误,但是我无法弄清楚如何在那里显示错误消息。

2 个答案:

答案 0 :(得分:41)

在客户端:

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"

    }
}

答案 1 :(得分:5)

您可以这样做,只需将Error Message添加到ModelState即可为您显示错误消息,前提是您已ValidationSummary()调用了您的视图。

要将错误添加到ModelState,请执行以下操作:

ModelState.AddModelError("ColumnNameOrErrorMessageKeyInState","error message goes here")