开发者

Event handler in masterpage accessing controls in the client page

I have a button on a masterpage, which when clicked, calls a method that takes an EventHandler previously saved to the viewstate, this method is on the client page, and executes it:

 protected void Save_Click(object sender, EventArgs e)
    {

        this.SaveButtonEvent += (EventHandler)ViewState["saveEvent"];
        if (this.SaveButtonEvent != null)
        {
            this.SaveButtonEvent(sender, e);

        }

    }

This then calls a very simple method on the client page:

protected void Button2_Click(object sender, EventArgs e)
{

    Label1.Text = TextBox2.Text;
}

However, the value of TextBox2 is incorrect, it is the value of the text box that was set when the page loaded (or if any other item on the pages changes it), the new value is not passed.

If I add a button to the client page, that calls the Button2_Click event directly, it开发者_运维百科 get's the correct value.

Is the reason I am not getting the correct value of the text box because the Event is called from the master page? Any solutions?

I should add, that this button is created dynamically, and the event delegate will vary, which is why I have to set it at run time. I need a way to set the delegate on a click, and persist this until it is changed again.


No, the reason is that you have saved the delegate in viewstate.

When you retrieve the delegate it still refers to the controls in the page where it was created, so you will be using controls from a page object that no longer exist.


Can you instead expose an event from the master page that can be handled in a content page ?

Master page:

public event EventHandler<EventArgs> AfterSave;
protected void Save_Click(object sender, EventArgs e)
{
    if(AfterSave != null) AfterSave(this, EventArgs.Empty);
}

Content page:

protected void Page_Load(object sender, EventArgs e)
{
    MasterPageObject m = (MasterPageObject)base.Master;
    m.AfterSave += onMasterSave;
}
private void onMasterSave(object sender, EventArgs e)
{
    // Your processing here
}

-- Pavel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜