【发布时间】:2010-12-04 03:53:18
【问题描述】:
我们有一个最初被禁用和选中的复选框。然后通过 javascript 在客户端启用它。如果用户随后取消选中该框并按下按钮以调用回发,则复选框的状态在服务器端保持为选中状态。这显然是不受欢迎的行为。这是一个例子。
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testcb.aspx.cs" Inherits="ESC.testcb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<script type="text/javascript">
function buttonClick() {
var cb = document.getElementById('<%= CheckBox1.ClientID %>');
cb.disabled = false;
cb.parentNode.disabled = false;
}
</script>
<div>
<asp:CheckBox ID="CheckBox1" runat="server" Checked="true" Enabled="false" />
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="buttonClick(); return false;" />
<asp:Button ID="Button2" runat="server" Text="Button2" OnClick="button2Click" />
</div>
</form>
</body>
</html>
以及服务器端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ESC
{
public partial class testcb : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void button2Click(object sender, EventArgs e)
{
string h = "";
}
}
}
所以我们在“string h”行中断并检查 CheckBox1.Checked 的值。这是真的,即使它在表单上未选中。
【问题讨论】:
-
这是因为当您从后面的代码中设置控件的属性时,您的页面的视图状态没有得到更新。
-
使用 HTML 控件代替服务器控件,我相信您的问题已经解决。
-
@Kamran,Viewstate 不是问题。
-
切换到 HTML 输入并不能解决问题。
标签: asp.net checkbox client postback