【问题标题】:Add error message to @Html.ValidationSummary将错误消息添加到 @Html.ValidationSummary
【发布时间】:2014-04-03 09:36:21
【问题描述】:

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

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

【问题讨论】:

  • 在客户端还是服务器端?

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


【解决方案1】:

在客户端:

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"

    }
}

【讨论】:

  • 谢谢 - 在这种情况下,我正在寻找客户端。我的问题是,如果我确实在“YourCustomValidator”中发现错误,我该如何显示我的特定错误消息?我已经有服务器端验证,它允许我通过“AddModelError”设置我想要的任何错误消息,但我想在 Javascript 中做同样的事情。
  • 您可以创建自定义逻辑以通过 JS 显示错误消息和/或您可以通过 C# 创建自定义验证属性类。你指的是哪一个?
  • 我不知道为什么这有32票,它根本没有回答这个问题。
【解决方案2】:

您可以这样做,只需将Error Message 添加到ModelState 应该会为您显示错误消息,前提是您在视图中调用了ValidationSummary()

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    相关资源
    最近更新 更多