简体   繁体   中英

Change Button on-click only if data is successfully stored to database without postback asp.net mvc5 EF6

成功存储数据后,更改按钮无后退

I have a situation wherein I have to change the button "Send Request" to "Request Sent". There are 'n' number of such buttons in my form and i need to change the buttons for all of them

The button should change only if data is successfully stored into the database without reloading the form. And here is how i have stored data to database.

public ActionResult SendRequest(string RequestId)
{
        MyRequest request = new MyRequest();
        request.UserId = loggedInUserId;
        request.FutureFriendId = RequestId;
        request.Status = RequestStatus.Pending;
        db.MyRequests.Add(request);
        db.SaveChanges();
        return View();
}

Later i might want to change the button "Request Sent" to "Cancel Request" to rollback the operation. Please give me a solution for the same. Thank you!

I would return a bool from instead the ActionResult. Your JS (Jquery) code should look something like this:

$(btn).click(function(){
$(btn).attr("disabled", "disabled").val("Sending Request...");
$.ajax({
            url: '/yoururl',
            type: 'GET',
            data: { RequestId: '12345' },
            async: true,
            success: function(returnParameters) {
                $(btn).attr("disabled", "disabled").val("Request Sent");
            },
            error: function(jqXHR, textStatus, errorThrown) {
$(btn).removeAttr("disabled").val("Send Request"); // error, reset.
            }
        });
});

This will give three situations to the button:

  1. Sending
  2. Sent
  3. Normal

I've also set the button to "disabled" to prevent more clicks incase it is in progress/the request was sent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM