我正在开发一个继承自DataBoundControl的控件。数据绑定有效,但由于某种原因,在回发时清除了视图状态?我已经尝试过各种各样的解决方案,比如让它实现ViewStateModeById属性,但没有任何效果。有人能指出我正确的方向吗?
public class Test : DataBoundControl, INamingContainer
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (this.Visible && !_isDataBound)
{
// If the developer wants to show it on click or something then they will have to call DataBind() themselves
// If this control has just been put on a page and there is no code behind then we need to make it get data and call DataBind
FlagForDataBinding();
DataBind();
}
}
protected override void OnPreRender(EventArgs e)
{
if (!_isDataBound || RequiresDataBinding)
{
DataBind();
}
base.OnPreRender(e);
}
private bool _isDataBound = false;
public override object DataSource
{
get { return Enumerable.Range(0, 10); }
set
{}
}
public virtual void FlagForDataBinding()
{
this.DataSource = null;
if (_isDataBound)
{
_isDataBound = false;
}
else
this.RequiresDataBinding = true;
}
protected override void PerformSelect()
{
if (!IsBoundUsingDataSourceID)
{
// If using .DataSource then databinding starts here
// (Because the the data has alredy been retrieved when doing .DataSource = )
OnDataBinding(EventArgs.Empty);
}
GetData().Select(CreateDataSourceSelectArguments(), OnDataReady);
RequiresDataBinding = false;
MarkAsDataBound();
OnDataBound(EventArgs.Empty);
}
protected virtual void OnDataReady(IEnumerable data)
{
if (IsBoundUsingDataSourceID)
{
// If using .DataSourceId then databinding starts here
OnDataBinding(EventArgs.Empty);
}
PerformDataBinding(data);
}
protected override void PerformDataBinding(IEnumerable data)
{
this.Controls.Clear();
if (data != null)
{
OutputItems((IEnumerable<int>)data);
}
base.PerformDataBinding(data);
}
public override void DataBind()
{
this.EnsureChildControls();
if (!_isDataBound || RequiresDataBinding)
{
base.OnDataBinding(EventArgs.Empty);
base.DataBind();
_isDataBound = true;
}
}
protected virtual void OutputItems(IEnumerable<int> items)
{
this.Controls.Clear();
foreach (var item in items)
{
var lnk = new LinkButton {Text = item.ToString(), CommandArgument = item.ToString()};
lnk.Click += lnk_Click;
this.Controls.Add(lnk);
}
this.Controls.Add(new Literal{Text = "Total: " + Total});
}
void lnk_Click(object sender, EventArgs e)
{
int toAdd = int.Parse((sender as LinkButton).CommandArgument);
Total += toAdd;
FlagForDataBinding();
}
public int Total {
get { return (int?) ViewState["Total"] ?? 0; }
set { ViewState["Total"] = value; }
}
}
答案 0 :(得分:0)
尝试在DataBoundControl上设置EnableViewState =“true”和ViewStateMode =“Enabled”。
此外,还要确保页面的EnableViewState =“true”。
https://msdn.microsoft.com/en-us/library/system.web.ui.control.enableviewstate(v=vs.110).aspx