InitialValue does not set in RequiredFieldValidator DDL
For some reason the dropdownlist's initial value doesnt get set. It always loads some random value instead. When I look into the markup I can see all the list items including the one with -1 value. I also tried clearing browser cache and explicitly setting the SelectedIndex/Value in code to 0/"-1", but cant seem to figure out what is going on. Any idea?
Here is how I am doing it:
<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>
Generated 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>
as you can see, it is randomly selecting Male. Alsow, I notice that, last time I fill the form I set 开发者_如何学运维it to Male before hitting submit. May be is it caching the selection?
Here is the .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"))
};
I tried your code, and it appears that the generated html didn't have the correct field bound to the "value" of the select options.
What you must get must have this format :
<select name="ctl00$MainContent$ddlGender" id="MainContent_ddlGender" class="select_Box">
<option selected="selected" value="-1">not set</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
In order to have this, I had to set the DataValueField of the DropDownList:
<asp:DropDownList ID="ddlGender" runat="server" CssClass="select_Box" OnPreRender="ddlGender_PreRender" DataValueField="Value" DataTextField="Text">
(Just replace the DataTextField and DataValueField with the name of the properties of your class)
It turns out it has something to do with load sequence of the controls. So, adding selectedindex to LoadGenders did the trick.
protected void LoadGenders(object sender, EventArgs e)
{
if (IsPostBack) return;
((DropDownList)sender).Items.AddRange(Constants.GenderWithSelect);
((DropDownList) sender).SelectedIndex = 0;
}
精彩评论