Home > Mobile >  In Razor Pages, how can I preserve the state of a checkbox which is not part of a form?
In Razor Pages, how can I preserve the state of a checkbox which is not part of a form?

Time:06-16

I have page that has checkbox that is used to expand/collapse some part of the page. This is client-side logic done in JavaScript.

I want to preserve the state of this checkbox for this particular page. Can Razor Pages do this automatically? I tried by adding bool property with [BindProperty(SupportsGet = true)] in PageModel but it doesn't work - when I check the checkbox and reload (HTTP GET) the checkbox is always false.

CodePudding user response:

Guessing that this toggle feature is user-specific, and that you want to persist their choice over a number of HTTP requests, I recommend setting a cookie using client-side code, which is user- or more accurately device-specific and can persist for as long as you need, and can be read on the server too.

CodePudding user response:

I want to preserve the state of this checkbox for this particular page. Can Razor Pages do this automatically?

No, since you don't send it to the backend it will not show it.

As Mike said, it better we could store it inside the client cookie or storage.

More details, you could refer to below codes:

<p>
  <input type="checkbox" id="cbox1" checked="checked">
  <label >This is the first checkbox</label>
</p>
 

@section scripts{
    <script>

        $(function(){
            var status = getValue();
                if(status === "true"){
                   $("#cbox1").attr("checked","checked");
                }else{
                  $("#cbox1").removeAttr("checked");
                }
        })

        $("#cbox1").click(function(){
            var re =  $("#cbox1").is(":checked")
            alert(re);
           createItem(re);
        
        });

        function createItem(value) {
                localStorage.setItem('status', value); 
            } 
 
            function getValue() {
                return localStorage.getItem('status');  
            } // Gets the value of 'nameOfItem' and returns it
            console.log(getValue()); //'value';
    </script>

}
  • Related