[英]ASP.Net LinkButton Does not update on first post back
在ListView控件的<ItemTemplate>
我使用的是LinkButton。 當列表填充時,它具有一組LinkButton。 鏈接按鈕文本是從使用數據源檢索的記錄中的列中生成的。
當我單擊LinkButton時,我需要在回發期間將其文本捕獲到隱藏字段或視圖狀態中,以便在發生頁面回發時將其顯示在Label或TextBox中。
但是不會發生在首頁回發上。 取而代之的是,我必須單擊LinkButton兩次,以兩次回發該值,才能在Label / TextBox中顯示該值。
我如何在第一篇回帖中完成它?
我已經嘗試過使用ListLink而不使用ListView進行相同操作,如下所示,並且得到相同的結果。
protected void LinkButton_Click(object sender, EventArgs e)
{
LinkButton selectedButton = (LinkButton)sender;
HiddenField1.Value = selectedButton.Text;
ViewState["LinkButtonText"] = selectedButton.Text;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(HiddenField1.Value))
{
Label1.Text = HiddenField1.Value;
}
TextBox1.Text = HiddenField1.Value;
if (ViewState["LinkButtonText"] != null)
{
if (!string.IsNullOrEmpty(ViewState["LinkButtonText"].ToString()))
{
ViewStateTextBox.Text = ViewState["LinkButtonText"].ToString();
}
}
}
好吧,這是由於服務器端方法執行的順序而發生的。 頁面先加載,然后控件按此順序單擊方法。 不再像現在那樣使用LinkButton控件的客戶端JavaScript函數OnClientClick更新隱藏字段,該函數將更新隱藏字段。
簡而言之,您只需要在首次加載時執行某些操作即可使用它。
Page.IsPostBack的經典用法是數據綁定/控件初始化。
if(!Page.IsPostBack)
{
//Control Initialization
//Databinding
}
不需要在每次回發中都重新創建持久保存在ViewState和ControlState上的內容,因此您需要檢查這種情況以避免執行不必要的代碼。
另一個經典用法是獲取和處理Querystring參數。 您無需在回發時執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.