【问题标题】:ASP.NET CheckBox state and PostBackASP.NET CheckBox 状态和 PostBack
【发布时间】:2010-10-30 05:28:31
【问题描述】:

我有一个简单的任务 - 在复选框状态更改时更改页面链接 - 但我是 ASP.NET 新手,遇到了一些麻烦。

我可以使用 HtmlControl 和 JavaScript 做同样的事情:

<script type="text/javascript" language="javascript">
  function checkbox_onChanged(checked) {
    if (checked) {
      document.location = '?type=request_in&show=all';
    }
    else {
      document.location = '?type=request_in&show=unapproved';
    }
  }

  function checkbox_onLoad(checkbox) {
    checkbox.checked = true;
  }
</script>

<form action="" method="get">
<input type="checkbox" name="checkbox"
  onload="checkbox_onLoad(this)"
  onchange="checkbox_onChanged(this.checked)" />Show all
</form>

但我想对用户隐藏它。所以我这样做:

<asp:CheckBox runat="server" ID="check" 
  OnCheckedChanged="check_CheckedChanged"
  AutoPostBack="True" Text="Show all" />

protected void check_CheckedChanged(object sender, EventArgs e)
{
  Response.Redirect(String.Format("{0}?type=request_in&show={1}", Request.Path, 
  checkViewRequestIn.Checked ? "all" : "unapproved"));
}

protected void Page_Load(object sender, EventArgs e)
{
  var show = Request["show"];
  if (!String.IsNullOrEmpty(show) && String.Equals(show, "all"))
  {
    checkViewRequestIn.Checked = true;
  }
}

但似乎加载时检查状态更改会再次引发事件,并且复选框始终处于选中状态!

Ans another question - 有没有其他方法可以重定向到同一页面而不给出它的文件名?我的意思是像在 JavaScript 中一样 - 只提供需要的变量?

【问题讨论】:

    标签: .net asp.net checkbox postback


    【解决方案1】:

    您可以从 ASP.NET 复选框中调用您的客户端“checkbox_onChanged”,只需从 Page_Load 中添加“onchange”,例如:

    protected void Page_Load(object sender, EventArgs e)
    {
       check.Attributes["onchange"] = "checkbox_onChanged(this.checked)";
    }
    

    查看源代码,您会看到 HTML 中发生了什么..

    【讨论】:

    • 感谢您的回答!但我不想在客户端这样做。您能否提示我如何仅在服务器端执行任务?我的软件范例需要最少的客户端操作。
    • 为什么要在查询字符串中发送信息?你可以访问 check.Checked 属性。注意 ASP.NET viewstate 将在回发之间保持复选框的状态,而无需测试 Request["show"]。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多