Search code examples
javascriptc#asp.net-coreasp.net-ajaxrazor-pages

Razor pages: How to dynamically change button properties (color,text) to reflect backend changes


In a non-Razor environment with simple HTML, CSS and AJAX, easily done, but from within Razor Pages?

Let's say I have a simple button based on a backend state of (success,danger) like:

<div id="UpdateButonStatusEvery2s">
  <button type="button" class="btn btn-success">Success</button>
</div>

and I want to reflect a change in the backend state to "danger" in the button

<div id="UpdateButonStatusEvery2s">
  <button type="button" class="btn btn-danger">Danger</button>
</div>

How do I achieve that?

I figured I have to run the usual setinterval() in AJAX, but how do I get the Razor backend to respond with the HTML fragment id="UpdateButonStatusEvery2s"?


Solution

  • You can try this code in your razor-page.

    First add this code in your startup:

    services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
    

    Then in your razor:

    @page
    @model ButtonDemoModel 
    @Html.AntiForgeryToken()
    
    <div id="UpdateButonStatusEvery2s">
        <button type="button" class="btn btn-success" value="success">Success</button>
    </div>
    @section Scripts
    {
        <script>
            $("button").click(function (e) {
                var data = $(this).val();
                $.ajax({
                    type: "POST",
                    url: "?handler=test",
                    data: { data: data },
                    beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                            $('input:hidden[name="__RequestVerificationToken"]').val());
                    },
                    dataType: "json",
                    success: function (response) {
                        if (response.result == "danger")
                        {
                            var newRow = '<button type="button" class="btn btn-danger" value="danger">' + response.result +'</button>';
                            $('#UpdateButonStatusEvery2s').html(newRow);
                        }
                    }
                });
            });
        </script>
    }
    

    The backend code:

     public class ButtonDemoModel : PageModel
    {
        public void OnGet()
        {
        }
        public IActionResult OnPostTest(string data)
        {
            //here you can change the data,do your logic.
            data = "danger";
            return new JsonResult(new { result = data });
        }
    }
    

    Test result: enter image description here