asp.Net   发布时间:2022-04-07  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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"

    }
}

大佬总结

以上是大佬教程为你收集整理的asp.net-mvc-3 – 向@ Html.ValidationSummary添加错误消息全部内容,希望文章能够帮你解决asp.net-mvc-3 – 向@ Html.ValidationSummary添加错误消息所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。