我想创建一个实现IPostBackDataHandler的标签,因为我想用javascript更改文本。如果我在那之后触发回发,那么我的文字就不见了。
我已经拥有的代码是:
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();
}
}
根本不起作用,我不知道如何看到文本被更改而PostCollection [postDataKey]始终为null。
答案 0 :(得分:1)
IPostBackDataHandler
接口用于输入。像span和div这样的元素不会存储在请求对象中。我只是实现必要的ViewState管理方法。以下是我开发的自定义网格组件的示例:
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();
}