我有一个启用了自动回发的下拉列表和一个RequiredFieldValidator。我希望当用户通过标签选择颜色时,HTML 颜色代码会出现在其旁边,并且当用户选择“选择”时,会出现“必需”一词。
这是代码:
<dx:LayoutItem ColSpan="1" FieldName="Color">
<LayoutItemNestedControlCollection>
<dx:LayoutItemNestedControlContainer runat="server"
<div style="display: flex; column-gap: 10px;">
<dx:LayoutItemNestedControlContainer runat="server">
<asp:DropDownList ID="cboColor" runat="server" Width="90px" AutoPostBack="True">
<asp:ListItem>Select</asp:ListItem>
<asp:ListItem>Black</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
</asp:DropDownList>
</dx:LayoutItemNestedControlContainer>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" ErrorMessage="Required" ControlToValidate="cboColor" InitialValue="Select" runat="server" ForeColor="Red" Font-Bold="true" Display="Dynamic" />
<dx:ASPxLabel ID="lblCompleteColor" runat="server" Text="" Font-Bold="true"></dx:ASPxLabel>
</div>
</dx:LayoutItemNestedControlContainer>
</LayoutItemNestedControlCollection>
</dx:LayoutItem>
和隐藏代码:
Protected Sub cboColor_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboColor.SelectedIndexChanged
lblCompleteColor.Text = GetCodeColor(cboColor.SelectedValue)
End Sub
Private Function GetCodeColor(ByVal sCodeColor As String) As String
Dim sResult As String = ""
Dim conSQL As New System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ETConnectionString").ConnectionString)
Dim cmdSQL As New System.Data.SqlClient.SqlCommand("SELECT CodiceColore FROM COLORI WHERE NomeColore='" & sCodeColor & "'", conSQL)
Try
conSQL.Open()
sResult = cmdSQL.ExecuteScalar()
Catch ex As Exception
sResult = ""
Finally
conSQL.Close()
End Try
Return sResult
End Function
问题是“必填”这个词在选择后很快就消失了。相反,如果我将 CausesValidation 属性添加到 DropDownList 中,则单词“Required”将保留,但旁边会显示之前选择的颜色。
<asp:DropDownList ID="cboColor" runat="server" Width="90px" AutoPostBack="True" CausesValidation="true">
...
</asp:DropDownList>
有什么解决办法吗?
CausesValidation="True" 应该存在,以便验证器正常工作。
问题的原因是验证器在回发之前在客户端进行检查,因此标签文本仍然是上次回发时分配的值。
回发前需要清除客户端的标签文本:
1- 在标签中添加 ClientIDMode="Static" 属性,以确保客户端 ID 与 ID="lblCompleteColor" 相同:
<dx:ASPxLabel ID="lblCompleteColor" runat="server"
ClientIDMode="Static"
Text=""
Font-Bold="true">
</dx:ASPxLabel>
2- 在下拉列表中添加 onchane 属性,其值为清除标签文本的函数:
<asp:DropDownList ID="cboColor" runat="server"
Width="90px"
AutoPostBack="True"
CausesValidation="True"
onchange="document.getElementById('lblCompleteColor').innerText='';">
...
...
</asp:DropDownList>