ASP.Net OnLoad停止事件处理

时间:2013-12-12 21:20:47

标签: asp.net postback pageload

我的WebForm页面中有一些验证码。当用户单击按钮并进行回发时。

处理Page_Load事件,然后处理Button1_Click事件。

如果在Page_Load上验证失败,我无法想办法停止处理Button1_Click事件。

这样做是一招吗?

由于

2 个答案:

答案 0 :(得分:0)

下面显示了4种变化。

 public partial class _Default : System.Web.UI.Page
    {
        private bool MyPageIsValid { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (Page.IsPostBack)
            {
                bool valid = false; /* some routine here */
                MyPageIsValid = valid;
            }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            if (this.MyPageIsValid)
            {
                this.TextBox1.Text = DateTime.Now.ToLongTimeString();
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {

            if (!this.MyPageIsValid) {return;}

            this.TextBox1.Text = DateTime.Now.ToLongTimeString();

        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            if (this.Page.IsValid)
            {
                this.TextBox1.Text = DateTime.Now.ToLongTimeString();
            }
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid) {return;}

            this.TextBox1.Text = DateTime.Now.ToLongTimeString();

        }
    }

答案 1 :(得分:0)

我认为最好在Button1_Click方法中检查验证条件,如下所示:

if (!this.IsValid()) { return; }

此外,如果您仍想检查Page_Load方法中的条件,只需在页面的类中添加简单的“bool isValid”标志,然后在Button1_Click中进行检查:

if (!this.isValid) { return; }
相关问题