Button value doesn't change after first click

I've got this button which changes a boolean in the database after clicking it. If the boolean PausedCMDBUpload = true the button should display UNPAUSE if the boolean is false, it should display PAUSE.

The button is changing the value in the database like intended, however after clicking the button the first time the page will refresh but the text on the button stays the same. After clicking it another time the text will change.

Does anyone have a idea why the value on the button isn't changing after the first click? Any help would be appreciated!

View

<script>
    function ClickButton1() {
        $.ajax({
            type: "POST",
            url: "@Url.Action("ClickButton1", "Devices")",
            async: true,
            success: function (msg) {
                ServiceSucceeded(msg);
            },
            error: function () {
                return "error";
            }
        });
    }
</script>

@if (@Model.ElementAt(0).PauseCMDBUpload == true)
    {
        <input id="Button1" type="button" value="UNPAUSE" onclick="ClickButton1(); document.location.reload(true)" />
    } 
    else
    {
        <input id="Button1" type="button" value="PAUSE" onclick="ClickButton1(); document.location.reload(true)" />
    }

Controller

[HttpPost]
public void ClickButton1()
{
    var entity = db.Devices;

    foreach (var device in entity)
    {
        if (device.PauseCMDBUpload == false)
        {
            device.PauseCMDBUpload = true;
        }
        else
        {
            device.PauseCMDBUpload = false;
        }
    }
    db.SaveChanges();
}

1 answer

  • answered 2021-01-17 03:48 meysam asadi

    You can change your code as follows:

    <script>
        function ClickButton1() {
            $.ajax({
                type: "POST",
                url: "@Url.Action("ClickButton1", "Devices")",
                async: true,
                success: function (msg) {
                    var btnText = $('#Button1').val();
                    if (btnText == "UNPAUSE")
                      $('#Button1').val('PAUSE');
                    else
                     $('#Button1').val('UNPAUSE');
                    ServiceSucceeded(msg);
                },
                error: function () {
                    return "error";
                }
            });
        }
    </script>
    
    @if (@Model.ElementAt(0).PauseCMDBUpload == true)
        {
            <input id="Button1" type="button" value="UNPAUSE" onclick="ClickButton1();" />
        } 
        else
        {
            <input id="Button1" type="button" value="PAUSE" onclick="ClickButton1();" />
        }