Search code examples
c#model-view-controllermodal-dialog

How to show the action confirmation window?


Good afternoon.

On the view there is a link Delete

<a class="nav-link text-dark" asp-controller="Home" asp-action="Delete">Delete</a>

when you click on which you want to show a dialog

  • with the text "Are you sure?"

  • Yes and No buttons

  • if we press No, then nothing happens (the dialog closes)

  • if we click Yes, then we call the method in the controller


Solution

  • Well in its simplest terms, you can use the Javascript confirmation alert box:

    <a class="nav-link text-dark" href="javascript:;" onclick="DeleteOperation();">Delete</a>
    

    Corresponding Javascript usin AJAX to post your data to the Controller:

    function DeleteOperation() {
    
        if (confirm("Are you sure you want to delete this entry?")) {
            //Get your id from the element where it is defined
            var idToDelete = $("#id").val();
            var json = { idToDelete: idToDelete};
    
            $.ajax({
                url: '@Url.Action("Delete", "Home")',
                type: 'post',
                dataType: "json",
                data: { "json": JSON.stringify(json)},
                success: function (data) {
                      if(data.status=="true")
                      {
                        alert(data.msg);
                        location.reload();
                      }
                      else
                      {
                        alert(data.msg);
                      }
                },
                error: function (error) {
                    alert("Error in deleting the entry. Please contact admin.");
                    location.reload();
                }
            });
        }
        else {
          return false;
        }
    }
    

    And your Controller method would look like this:

    using System.Web.Script.Serialization;
    
    [HttpPost]
    public JsonResult Delete(string json)
    {
        var serializer = new JavaScriptSerializer();
        try
        {
            dynamic jsondata = serializer.Deserialize(json, typeof(object));
    
            //Get your variables here from AJAX call
            int id = Convert.ToInt32(jsondata["idToDelete"]);
            //Can be webservice call or DB call
            var deleteoperationresult = DeleteOperation(id);
            if(deleteoperationresult)
            {
                return Json(new { status = "true", msg = "Successfully deleted" }); 
            }
            else
            {
                return Json(new { status = "false", msg = "Could not delete the entry!" });
            }
        }
        catch (Exception ex)
        {
            return Json(new { status = "false", msg = ex.Message});
        }
    }