Question

I have some checkboxes and a dropdownlist when the value changes I want to refresh the page while passing the new value. I tried using autopostback; however, the value is already in the url previously so when the postback occurs the value never changes.

Example:

CurrentPage: page.aspx?tab=Home&checkbox=True

Then I uncheck the checkbox so I want it to go to the following page...

IntendedPage: page.aspx?tab=Home&checkbox=False

But instead I the autopostback gives me this page...

DestinationPage: page.aspx?tab=Home&checkbox=True

Because, I handle the building of the url through a function on my page. Perhaps I'm doing something wrong by this point. If so I'd be happy to be corrected on my current setup. What I think I need to know though is how to load a custom URL on the checkbox.checkchanged event. I hope this made sense, if not let me know I'll try and clarify it. Thanks!

Was it helpful?

Solution

This is very easy to do through javascript. First add onclick="checkCheckBox(this);" to your checkbox.

<script language = "javascript" type="text/javascript"> 
function checkCheckBox(checkbox) {
        if (checkbox.checked) {
            window.location.href = '../page.aspx?tab=Home&checkbox=True';
        }
        else {
            window.location.href = '../page.aspx?tab=Home&checkbox=False';
        }
    }
</script>

This should do it pretty easily.

OTHER TIPS

You could try something like this ( I have not tested, it was just an idea).

 protected void CheckBox1_CheckedChanged ( object sender, EventArgs e )
    {
        string url = "page.aspx?tab=Home&checkbox="+ CheckBox1.Checked.ToString();
        Response.Redirect ( url );
    }

And then on the page:

<asp:CheckBox ID="CheckBox1" runat="server" 
oncheckedchanged="CheckBox1_CheckedChanged" />

VB.NET Conversion

Protected Sub CheckBox1_CheckedChanged(sender As Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
       Dim url = "page.aspx?tab=Home&checkbox=" & CheckBox1.Checked.ToString()
       Response.Redirect(url)
End Sub

This behavior is caused by the viewstate. The checkbox use it to persists its property, especially the checked property.

Actually, there is no out of the box link between a control and query string.

In your case, you will have two options, depending on your needs :

  • in the Checked event, build the expected url, and redirect the user to this page. The drawback is that you "loose" the viewstate and thus, the controls' state.
  • instead of using postbacks, use client side script (jQuery is your friend) to hide/show parts of the page. If the url matters, use # in the urls because it does allow staying on the same page.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top