Asp.net
ASP.NET DropDownList 在回發時不保留所選項目
我有一個在 Page_Load 事件中填充的 ASP DropDownList,在我選擇一個項目並點擊一個按鈕後,所選項目被清除並且 DropDownList 中的第一個項目被選中。(DropDownList 僅在頁面未回發時填充)
if (!IsPostBack) { List<Country> lCountries = new List<Country>(); List<CompanySchedule> lCompanySchedules = new List<CompanySchedule>(); this.Load_Countries(lCountries); this.Load_Schedules(lCompanySchedules); if (personnelRec == null) { personnelRec = new Personnel(); } if (Request.QueryString["UA"] != null && Convert.ToInt32(Request.QueryString["UA"].ToString()) > 0) { userAccount.ID = Convert.ToInt32(Request.QueryString["UA"].ToString()); App_Database.Snapshift_Select_Helper.SNAPSHIFT_SELECT_PERSONNEL_APP_ACCOUNT(ref userAccount); } this.imgEmployeePicture.ImageUrl = "./images/Employees/nophoto.gif"; if (Request.QueryString["EI"] != null && Convert.ToInt32(Request.QueryString["EI"].ToString()) > 0) { this.Load_PersonnelRec(Convert.ToInt32(Request.QueryString["EI"].ToString())); } else { this.lblChangeDirectionHead.Enabled = false; this.lblChangeDirections.Enabled = false; this.lbSchedules.Disabled = true; } }
頁面生命週期執行以下操作(加上與您的問題無關的其他步驟):
OnInit- 從 ViewState 填充控制項(在回發期間)
- 設置選定的值(回發期間)
Page_Load您需要啟用 ViewState,以便它可以在“選擇”項目之前填充列表。在這種情況下,請確保您不會在 Page_Load 中重新填充並失去所選值。做類似的事情
if (!IsPostback) { // Populate }否則,您必須
OnInit在每個頁面請求的事件中手動填充列表。Page_Load在生命週期中為時已晚,因此所選項目失去。編輯:
DropDownList還必須設置有效值(與瀏覽器中顯示的文本分開)。這是通過DataValueField屬性完成的。每個值都必須是唯一的,否則只會選擇第一個重複項。如果您在瀏覽器中查看 HTML 原始碼,您應該有:<select> <option value="unique_value1">Displayed text1</option> <option value="unique_value2">Displayed text2</option> </select>唯一值用於在伺服器端選擇正確的項目。