我看過一些類似問題的答案,但我仍然無法弄清楚這一點。我認爲我誤解了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對象包含零個項目,並且沒有選定的值。不知何故,我在選擇項目和提交之間丟失了填充項目。任何想法我做錯了什麼?
但是,如果我這樣做,選定的索引將始終爲0,因爲它是單擊提交後,但在調用RegisterUser_CreatedUser之前正在重新填充。 – Erix 2010-12-02 14:49:28