添加错误消息@ Html.ValidationSummary [英] Add error message to @Html.ValidationSummary

查看:165
本文介绍了添加错误消息@ Html.ValidationSummary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用标准MVC3剃刀意见与不显眼的JavaScript验证,使用 @ Html.ValidationSummary 在表单的顶部显示它们。如果标准验证(如的东西[必需] )通过,我再运行,当用户点击了提交按钮触发一些非常定制的客户端验证。 (验证看起来在多个表单元素,以确保他们的正常组已检查等,所以它不是那么简单,只是创造了单场新的自定义验证器)。

I'm using standard MVC3 Razor views with unobtrusive Javascript validation, using @Html.ValidationSummary to show them at the top of the form. If the standard validations (things like [Required]) pass, I then run some very custom client-side validation that fires when the user hits the Submit button. (The validation looks across a number of form elements to make sure that the proper set of them have been checked, etc., so it's not as simple as just creating a new custom validator for a single field).

我想可能出现的错误(S)我有建造在的ValidationSummary 列表中显示,但我不能弄清楚如何得到错误信息出现在那里。

I'd like the possible error(s) I construct there to be shown in the ValidationSummary list, but I can't figure out how to get the error message to appear there.

推荐答案

在客户端:

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());
    });
});

或在服务器端:

觉得你有这样一个模型:

Think you have a model like this:

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"

    }
}

这篇关于添加错误消息@ Html.ValidationSummary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆