由于某种原因,下拉列表的初始值未设置。它总是加载一些随机值。当我查看标记时,我可以看到所有列表项,包括具有 -1 值的项。我还尝试清除浏览器缓存并将代码中的 SelectedIndex/Value 显式设置为 0/“-1”,但似乎无法弄清楚发生了什么。任何的想法?
这是我的做法:
<asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="LoadGenders">
</asp:DropDownList>
<div class="error">
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorGender"
Runat="server"
Enabled="true"
InitialValue="-1"
ControlToValidate="ddlGender"
SetFocusOnError="true"
Display="Dynamic">Gender Required</asp:RequiredFieldValidator>
</div>
生成的 HTML:
<select name="pagecolumns_0$pagecontent_1$contentleftcol_0$ctl00$ddlGender" id="pagecolumns_0_pagecontent_1_contentleftcol_0_ctl00_ddlGender" class="select_Box">
<option value="-1">--Select Gender--</option>
<option selected="selected" value="M">Male</option>
<option value="F">Female</option></select>
如您所见,它是随机选择男性。另外,我注意到,上次填写表格时,我在点击提交之前将其设置为男性。可能是缓存选择吗?
这是.cs:
protected void LoadGenders(object sender, EventArgs e)
{
if (IsPostBack) return;
((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
}
public static ListItem[] GenderWithSelect = (new[] { new ListItem("--Select Gender--", "-1") }).Concat(Gender).ToArray();
public static ListItem[] Gender = new[]
{
(new ListItem("Male","M")),
(new ListItem("Female","F"))
};