Create a custom label that implements IPostBackDataHandler

不羁的心 提交于 2020-01-15 16:38:31

问题


I want to create a label that implements the IPostBackDataHandler, because I want to change the text with javascript. If I trigger a postback after that, than my text is gone.

The code that I already have is this:

public class CustomLabel : Label, IPostBackDataHandler
{
  protected override void OnPreRender(EventArgs e)
  {
    base.OnPreRender(e);

    if (Page != null)
      Page.RegisterRequiresPostBack(this);
  }

  public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
  {
    this.Text = postCollection[postDataKey];
    return true;
  }

  public void RaisePostDataChangedEvent()
  {
    //throw new NotImplementedException();
  }
}

It is not working at all, I don't get how I should see that the text is changed and PostCollection[postDataKey] is always null.


回答1:


The IPostBackDataHandler interface is intended for inputs. Elements like spans and divs don't get stored in the request object. I would just implement the necessary ViewState management methods. Here's an example from a custom grid component that I developed:

protected override void LoadViewState(object savedState)
{
    if (savedState != null)
    {
        object[] state = (object[])savedState;

        if (state[0] != null)
            base.LoadViewState(state[0]);
        if (state[1] != null)
            ((IStateManager)ItemStyle).LoadViewState(state[1]);
        if (state[2] != null)
            ((IStateManager)headerStyle).LoadViewState(state[2]);
        if (state[3] != null)
            ((IStateManager)AlternatingItemStyle).LoadViewState(state[3]);
    }
}

protected override object SaveViewState()
{
    object[] state = new object[4];

    state[0] = base.SaveViewState();
    state[1] = itemStyle != null ? ((IStateManager)itemStyle).SaveViewState() : null;
    state[2] = headerStyle != null ? ((IStateManager)headerStyle).SaveViewState() : null;
    state[3] = alternatingItemStyle != null ? ((IStateManager)alternatingItemStyle).SaveViewState() : null;

    return state;
}

protected override void TrackViewState()
{
    base.TrackViewState();

    if (itemStyle != null)
        ((IStateManager)itemStyle).TrackViewState();
    if (headerStyle != null)
        ((IStateManager)headerStyle).TrackViewState();
    if (alternatingItemStyle != null)
        ((IStateManager)alternatingItemStyle).TrackViewState();
}


来源:https://stackoverflow.com/questions/8181471/create-a-custom-label-that-implements-ipostbackdatahandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!