1

我有一个控件,应该提示用户选择会话的 customerId 或页面的旧视图状态 customerId。为此,该控件在代码后面的验证中基于

在回发时,如何向验证摘要添加错误消息?

当单步执行代码时,我看到 err.IsValid 设置为 false。但是当我到达 Page.IsValid 并查看验证器时,它被设置为 true。可以提供任何信息来帮助我理解为什么这没有按照我的预期进行,我们将不胜感激。

后面的代码

public partial class CustomerChanged : System.Web.UI.UserControl
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        this.Page.PreLoad += Page_PreLoad;
    }

    void Page_PreLoad(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState.Add("CustID", Globals.CurrentCust.CustId);
        }
        if (IsPostBack)
        {
            if (Convert.ToInt32(ViewState["CustID"]) != Globals.CurrentCust.CustId)
            {
                btnOldCustId.Text = "Old CustID \n" + ViewState["CustID"].ToString();
                btnNewCustId.Text = "New CustID \n" + Globals.CurrentCust.CustId.ToString();
                btnOldCustId.OnClientClick = string.Format("return changeCustomer({0},'{1}');", ViewState["CustID"].ToString(), Globals.GeneralSiteUrl);

                System.Web.UI.WebControls.CustomValidator err = new System.Web.UI.WebControls.CustomValidator();
                err.IsValid = false;
                err.ErrorMessage = "The customer has changed.";
                Page.Validators.Add(err);
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {            
        if (IsPostBack)
        {
            Page.Validate();
            if (!Page.IsValid)
            {                    
                ScriptManager.RegisterStartupScript(this, this.GetType(), "CustomerChangedModalDialog", "ShowCustomerChangedModalDialog();", true);
            }
        }
    }
    protected void btnNewCustId_Click(object sender, EventArgs e)
    {
        Response.Redirect(Request.RawUrl);
    }
}
4

1 回答 1

2

您可以使用以下命令将错误消息添加到验证摘要:

if (IsPostBack)
{
    Page.Validate();
    var valid = CustomValidate();

    if(valid && Page.IsValid)
    {
    }               
}

protected bool CustomValidate()
{
     var valid = true;
     ///do your validation here

     var validator = new CustomValidator();
     validator.IsValid = false;
     valid = validator.IsValid;
     Validator.ErrorMessage = "Error....";        
     this.Page.Validators.Add(validator);
     return valid;
}
于 2013-01-10T16:46:17.660 回答