2010-12-02 44 views
0

我看過一些類似問題的答案,但我仍然無法弄清楚這一點。我認爲我誤解了ASP.NET如何工作。爲什麼我的DropDownList在回發時爲空?

在標準的ASP.Net 4.0'創建新帳戶'表單中,我添加了一個DropDownList,其中包含要爲新帳戶選擇的角色。在aspx頁面,控制看起來是這樣的:

<asp:DropDownList ID="RoleList" Width="100px" runat="server"></asp:DropDownList> 

我然後填充列表在Page_Load事件:

protected void Page_Load(object sender, EventArgs e) 
    { 
     RegisterUser.ContinueDestinationPageUrl = Request.QueryString["ReturnUrl"]; 

     if (Page.IsPostBack) 
     { 
      return; 
     } 

     //Set the Role List Selections 
     DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList"); 

     //set the role list 
     String[] roles = Roles.GetAllRoles(); 
     foreach (String role in roles) 
     { 
      roleList.Items.Add(new ListItem(role, role)); 
     } 
    } 

我可以看到/選擇生成的HTML的作用。點擊創建用戶的「提交」按鈕時出現問題:

protected void RegisterUser_CreatedUser(object sender, EventArgs e) 
    { 
     FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */); 

     string continueUrl = RegisterUser.ContinueDestinationPageUrl; 
     if (String.IsNullOrEmpty(continueUrl)) 
     { 
      continueUrl = "~/"; 
     } 

     //set user role 
     DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList"); 
     Roles.AddUserToRole(RegisterUser.UserName, roleList.SelectedValue); 

     Response.Redirect(continueUrl); 
    } 

此處,roleList對象包含零個項目,並且沒有選定的值。不知何故,我在選擇項目和提交之間丟失了填充項目。任何想法我做錯了什麼?

回答

9

把你的下拉列表加載到OnInit函數,而不是 - 那麼它必須正確安裝時RegisterUser_CreatedUser叫做:

protected override void OnInit(EventArgs e) 
{ 
    base.OnInit(e); 

    //Set the Role List Selections 
    DropDownList roleList = (DropDownList)RegisterUser.CreateUserStep.ContentTemplateContainer.FindControl("RoleList"); 

    //set the role list 
    String[] roles = Roles.GetAllRoles(); 
    foreach (String role in roles) 
    { 
     roleList.Items.Add(new ListItem(role, role)); 
    } 
} 
0

下面的代碼繞過了正確的頁面加載數據綁定。

if (Page.IsPostBack) 
{ 
    return; 
} 

您需要每次都綁定此控件,以便在調用單擊事件時存在這些值。您也可能遇到事件錯誤,以便對不再存在的選定項目進行操作。

+0

但是,如果我這樣做,選定的索引將始終爲0,因爲它是單擊提交後,但在調用RegisterUser_CreatedUser之前正在重新填充。 – Erix 2010-12-02 14:49:28

0

您是否嘗試用以下條件擁抱您的綁定?

if (!Page.IsPostBack) 
{ 
    //Binding goes here 
} 
+0

這相當於我已經擁有的。 – Erix 2010-12-02 15:00:24

+1

@SP - 的確如此,但ncakmak的格式化是做這類事情的更爲標準的方式,所以您可能希望以這種格式進行操作,以便其他人更容易理解您的代碼。 – 2010-12-02 15:19:53

1

我有一個類似問題的單選按鈕選擇的變化會自動回發頁面,下拉列表項將在頁面返回後消失。

解決方案

檢查IIS - >你的網站 - >頁面&控制 - >啓用視圖狀態&啓用的sessionState應設置爲true。

希望這會有所幫助。

相關問題