これは私のお気に入りのトリックです:)
私たちのシナリオは、最初にコントロールをレンダリングすることです。次に、ユーザーからの入力を使用して、さらにコントロールをレンダリングし、イベントに応答させます。
ここで重要なのは状態です。コントロールが PostBack に到着したときの状態を知る必要があるため、ViewState を使用します。この問題は、ニワトリが先か卵が先かという問題になります。ViewState は呼び出し後まで使用できませんLoadViewState()
が、イベントを正しく発生させるには、その呼び出しの前にコントロールを作成する必要があります。
秘訣はオーバーライドすることです。これによりLoadViewState()
、SaveViewState()
物事を制御できます。
(以下のコードは大雑把で、メモリからのものであり、おそらく問題があることに注意してください)
private string searchQuery = null;
private void SearchButton(object sender, EventArgs e)
{
searchQuery = searchBox.Text;
var results = DataLayer.PerformSearch(searchQuery);
CreateLinkButtonControls(results);
}
// We save both the base state object, plus our query string. Everything here must be serializable.
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
return new object[] { baseState, searchQuery };
}
// The parameter to this method is the exact object we returned from SaveViewState().
protected override void LoadViewState(object savedState)
{
object[] stateArray = (object[])savedState;
searchQuery = stateArray[1] as string;
// Re-run the query
var results = DataLayer.PerformSearch(searchQuery);
// Re-create the exact same control tree as at the point of SaveViewState above. It must be the same otherwise things will break.
CreateLinkButtonControls(results);
// Very important - load the rest of the ViewState, including our controls above.
base.LoadViewState(stateArray[0]);
}