Create a custom label that implements IPostBackDat

2019-08-06 23:08发布

问题:

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();
}