日期:2014-05-18  浏览次数:20874 次

js控制DropDownList 并提交的问题
ceshi.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ceshi.aspx.cs" Inherits="admin_ceshi2" %>
<head runat="server">
  <title>无标题页</title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
  <asp:DropDownList ID="DropDownList1" runat="server">
  <asp:ListItem>1</asp:ListItem>
  <asp:ListItem>2</asp:ListItem>
  </asp:DropDownList>
  <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /></div>
  </form>
  <script type="text/javascript" language="javascript">
  var dropDownList1 = document.getElementById("DropDownList1");
  eOption = document.createElement('OPTION');
  eOption.text = "ceshi";
  eOption.value = "ceshi";
  dropDownList1.options.add(eOption);
  dropDownList1.options[dropDownList1.length-1].selected=true;
   
  </script>

</body>
</html>

ceshi.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class admin_ceshi2 : System.Web.UI.Page
{
  protected void Button1_Click(object sender, EventArgs e)
  {
  Response.Write(DropDownList1.Text); //Request.Form["DropDownList1"]
  }
}


点击botton后,显示错误如下

回发或回调参数无效。在配置中使用 <pages enableEventValidation="true"/> 或在页面中使用 <%@ Page EnableEventValidation="true" %> 启用了事件验证。出于安全目的,此功能验证回发或回调事件的参数是否来源于最初呈现这些事件的服务器控件。如果数据有效并且是预期的,则使用 ClientScriptManager.RegisterForEventValidation 方法来注册回发或回调数据以进行验证。


存分不多,不过请问各位大虾帮忙看下该如何解决?

------解决方案--------------------
因为DropDownList是服务器端控件,有ViewState等验证数据, 你的js对其修改被认为是"非法的"修改.

如果你要这么用,请使用HtmlControls 而不要用WebControls, (也就是用runat=Server的Select代替DropDownList)

如果一定要用DropDownList, 则把ViewState禁用掉,如果一定要有ViewState又一定要用DropDownList,可以设置EnableEventValidation="false",不过这会造成安全隐患,你需要在代码中好好验证用户的输入.否则别人可以做个网页模拟Post非法数据对服务器发起攻击

还有最后一种方法是同时修改ViewState中的base64值,不过大部分时候这几乎是一种不可接受的方案