从code后面添加错误消息,验证摘要 [英] Adding error message to validation summary from code behind

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

问题描述

我在做类似下面在Web窗体应用程序;

I am doing something like below on a web forms application;

protected void button_transfer_search_Click(object sender, EventArgs e) {

    Page.Validate("val1");

    if (!Page.IsValid && int.Parse(txtArrivalDateTrf.Text) + 5 < 10) {
        return;
    }

另外,我有我的aspx文件如下code;

also, I have following code on my aspx file;

<div class="search-engine-validation-summary">
    <asp:ValidationSummary ValidationGroup="transfer" runat="server" ShowMessageBox="false" />
</div>

我的问题是如何添加一个错误信息页面返回之前,这样验证摘要可以抓住这一点,显示它。我知道我们可以在MVC中很容易地做到这一点,但我还没有想出怎么做,在网页表单。谢谢!

my question is how to add an error message to the page before return so that validation summary can grab that and displays it. I know we can do this in mvc easily but I haven't figured out how to do that in web forms. thanks !

推荐答案

每当我发现这种情况,这是我做的:

Whenever I find this situation this is what I do:

var val = new CustomValidator()
{
   ErrorMessage = "This is my error message.",
   Display = ValidatorDisplay.None,
   IsValid = false,
   ValidationGroup = vGroup
};
val.ServerValidate += (object source, ServerValidateEventArgs args) => 
   { args.IsValid = false; };
Page.Validators.Add(val);

在我的ASPX code我有一个ValidationSummary控件使用的ValidationGroup设置为相同的值 vGroup

然后,我已经装尽可能多的CustomValidators(或任何其他类型的验证器)由codebehind后,我想我只需拨打

Then, after I have loaded as many CustomValidators (or any other kind of validators) by codebehind as I want I simply call

Page.Validate()
if (Page.IsValid)
{
    //... set your valid code here
}

Page.Validate()呼叫调用所有code-后面插入验证器的拉姆达联的方法,如果任何虚假返回页面无效,有没有执行code返回。否则,该页面会返回一个有效的值,并执行有效的code。

The call to Page.Validate() calls the lambda-linked method of all code-behind inserted validators and if any returns false the page is invalid and returned with no code executed. Otherwise, the page returns a valid value, and executes the valid code.

这篇关于从code后面添加错误消息,验证摘要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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