Home > database >  How to dynamically change Button Attr in Razor Page?
How to dynamically change Button Attr in Razor Page?

Time:12-23

I am trying to get a button to toggle between two states within MVC Razor View.

Startup.cs (Configuring Antiforgery Service)

public void ConfigureServices(IServiceCollection services)
{
   services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
   services.AddControllersWithViews();
}

View (with JS)

@Html.AntiForgeryToken()

<div >
    <div  style="background-color: none">
        <button id="ms1" >Misc Buttons 1</button>
        <button id="ms2" >Misc Buttons 2</button>
    </div>

    <div id="UpdateButonStatusEvery2s" style="background-color: none">
        <button id="btnPause"  value="Pause">Pause</button>
    </div>

    <div  style="float: right; background-color: none">
        <button id="ms3" >Misc Buttons 3</button>        
        <button id="ms4" >Misc Buttons 4</button>
        <button id="ms5" >Misc Buttons 5</button>
        <button id="ms6" >Misc Buttons 6</button>
    </div>
</div>

@section Scripts
{
    <script type="text/javascript">
        $("#btnToggle").click(function (e) {
            alert("test");
            var data = $(this).val();
            $.ajax({
                type: "POST",
                url: '../Home/OnPostTest/',
                data: { data: data },
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                dataType: "json",
                success: function (response) {
                    if (response.result == "ToggleDanger") {
                        var newRow = '<button id="btnToggle"  value="Danger">Danger</button>';
                        $('#UpdateButonStatusEvery2s').html(newRow);
                    }
                    else if (response.result == "TogglePause") {
                        var newRow = '<button id="btnToggle"  value="Pause">Pause</button>';
                        $('#UpdateButonStatusEvery2s').html(newRow);
                    }
                }
            });
        });
    </script>
}

Controller

public IActionResult OnPostTest(string data)
{
    string responseData;

    if (data == "Danger")
    {
        responseData = "TogglePause";
        return new JsonResult(new { result = responseData });
    }
    else if (data == "Pause")
    {
        responseData = "ToggleDanger";
        return new JsonResult(new { result = responseData });
    }

    return new JsonResult(null);
}

With this, it can toggle from the initial "Pause" button to the "Danger" button. However, the updated div with the new danger button HTML does not recognize the button ID as alert("test"); does not trigger at all upon clicking "Danger" btn.

It's based on this enter image description here

  • Related