页面.EnableEventValidation = false不识别新的下拉列表值

Page.EnableEventValidation = false does not recognize new dropdownlist values

本文关键字:下拉列表 识别 EnableEventValidation false 页面      更新时间:2023-09-26

我的测试表单有1个dropdownlist和2个buttons

<form id="form1" runat="server">
    <asp:DropDownList ID="DropDownListTest" runat="server" >
        <asp:ListItem>Value 0</asp:ListItem>
        <asp:ListItem>Value 1</asp:ListItem>
        <asp:ListItem>Value 2</asp:ListItem>
    </asp:DropDownList>
<asp:Button ID="ButtonClient" runat="server" Text="Button" OnClientClick="ChangeDropDown(); return false;" />
<asp:Button ID="ButtonServer" runat="server" Text="Server" onclick="ButtonServer_Click" />
</form>

这是javascript函数ChangeDropDown():

function ChangeDropDown() {
        for (i = document.getElementById("<%=DropDownListTest.ClientID%>").options.length - 1; i >= 0; i--) {
            document.getElementById("<%=DropDownListTest.ClientID%>").remove(i);
        }
        var opt = document.createElement("option");
        opt.text = "Complete";
        opt.value = "Complete";
        document.getElementById("<%=DropDownListTest.ClientID%>").options.add(opt);

        var opt2 = document.createElement("option");
        opt2.text = "Not Complete";
        opt2.value = "Not Complete";
        document.getElementById("<%=DropDownListTest.ClientID%>").options.add(opt2);
} 

后面的代码是:

    protected void ButtonServer_Click(object sender, EventArgs e)
    {
        string val = this.DropDownListTest.SelectedValue;
    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Page.EnableEventValidation = false;
        //"Invalid postback or callback argument" if I remove this.
    }

假设我点击button ButtonClient(这会改变下拉框的值),选择"完成",然后点击ButtonServer。在codebehind中,this.DropDownListTest.SelectedValue的值等于" value 0"而不是"Complete"。

我明白为什么我得到的问题,但有没有另一个解决方案除了添加项目代码背后?

您无法以标准方式获得该值,因为服务器不知道下拉列表的项已被更改。

但是,您可以直接从请求中获取值:

protected void ButtonServer_Click(object sender, EventArgs e)
{
    string val = Request[this.DropDownListTest.UniqueID];
}