views:

2559

answers:

1

I have a simple task - to change page link on checkbox state change - but I'm new to ASP.NET and have some trouble.

I can do the same using HtmlControl and 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>

but I want to hide it from users. So I do:

<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;
  }
}

But it seems that check state change on load raises the event again and checkbox becomes checked always!

Ans another question - is there any other way to redirect to the same page without giving it's filename? I mean like in JavaScript - only giving variables needed?

+2  A: 

You can call your client-side 'checkbox_onChanged' from the ASP.NET checkbox, just add the 'onchange' from the Page_Load, e.g:

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

View source and you'll see what is happening in the HTML..

russau
Thanks for answer! But I do not want to do that on client-side. Could you please tip me how to do the task only on server side? My software paradigm requires minimal amount of client-side actions.
abatishchev
why are you sending the info around in the querystring? you can just access the check.Checked property. note ASP.NET viewstate will maintain the state of your checkbox between postbacks without you having to test Request["show"].
russau
Thanks you a lot!!
abatishchev