ASP.net MVC Confirmation Dialog

 

To get a decent looking dialog working without too much hassle, we will make use of the jQuery UI library.

First install NuGet package jQueryUI.Combined, and then, just add the following code (adjust as needed).
Notice that the Delete link (href) calls the confirmDelete JavaScript method.

foreach (var item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Title)
        </td>
        <td>
            <a href="@Url.Action("Edit", "Notes", new { noteId = item.NoteId })">
                <i class="glyphicon glyphicon-edit"></i>
                Edit
            </a>|
            <a href="#" onclick="javascript:confirmDelete('@item.NoteId')">
                <i class="glyphicon glyphicon-trash"></i>
                Delete
            </a>
        </td>
    </tr>
}

<div id="dialogBox" title="Confirm Delete"></div> 

<script src="~/Scripts/jquery-3.6.0.js"></script>
<script src="~/Scripts/jquery-ui-1.12.1.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />

<script type="text/javascript">
    let noteId = ''; 

    $(function () {
        $.noConflict();
        $('#dialogBox').dialog({
            resizable: false,
            height: 200,
            autoOpen: false,
            modal: true,
            buttons: {
                "Yes": function () {
                    var url = '@ViewBag.baseUrl' + "Notes/Delete/" + noteId;
                   window.location.replace(url);
                    $(this).dialog("close");
                },
                "No": function () {
                    $(this).dialog("close");
                }
            }
        });
    });

    function confirmDelete(nid)
    {
        noteId = nid;
        document.getElementById("dialogBox").innerHTML = "Are you sure you want to delete note:<br/> <b>" + nid + "</b>?";
        $('#dialogBox').dialog("open");
    }

</script>


Comments