Share via


ASP.NET Core : How to show a confirmation dialog with jquery

1 Introduction

This article explains how to show a confirmation dialog when a button clicks and a row clicks. It creates a web application using ASP.NET Core in Visual Studio 2017. It has used Jquery and Jquery ui libraries to create the confirmation dialog box.

↑ Return to Top

2 Background

↑ Return to Top

3 Create a Web application using ASP.NET Core in Visual Studio 2017

Let's create a web application using .NET Core in Visual Studio 2017. Student can submit their assignments to the system. Let's see how we can show a confirmation box when a student deletes and when an assignment deletes from the system.

↑ Return to Top

3.1 Create a ASP.NET Core web application

Create a new ASP.NET Core web application like this,

↑ Return to Top

3.2 Create Student Model

Let's create student model. Add student class into Models folder.

public class  Student 
{ 
 public int  Id { get; set; } 
 public string  Name { get; set; } 
 public int  Age { get; set; } 
 public int  Year { get; set; } 
}

↑ Return to Top

3.3 Create Student Controller

Click on Controllers folder and add a new controller, this dialog box comes up, It allows you to add packages and references to your project as you need.
It adds all the packages you need to work with entity framework database context,
Let's select Minimal dependencies, since we don't need error pages and bundling features for our web application

After adding dependencies into your application, let's add a controller, select MVC controller with views, using Entity Framework

Select model class as student and create new data context class as below,

Click on Add, It will add StudentsController to your project,

If you check the solution, along with Studentscontroller, database context class is created as below

↑ Return to Top

3.4 Create the database

Now, let's create the database, go to solution explorer and right click on it, select Open Folder in File explorer, and open a cmd prompt from that location,
run dotnet command, it shows .net core version

Run dotnet ef command to check whether Entity framework is available, it says entity framework is not available,

Right click on web application and select Edit .csproj

Check .csproj, it shows all the available packages for your solution and tools, We need to add EFCore tools to run dotnet-ef command, let's add it into tools section


 <dotnetclitoolreference include="Microsoft.EntityFrameworkCore.Tools.DotNet" version="1.0.0">

Let's build the solution and run dotnet - ef command

Let's create student table in the database, create migrations using following command,

It will create student table script as follows,

Run database update command as below to run this script on our database,

student database is created as below, view SQL server object explorer and you can check student table is available

Let's run the application and navigates to the students page, click on create new and create few students

↑ Return to Top

4 Show a confirmation box when a student edits

Let's try to show a confirmation dialog, when you try to edit a student
Go to solution explorer and expand wwroot and navigate into jquey in lib folder, it shows jquery library, Let's refer it in our Edit view

Let's give save button a id, as btnSave, we can refer to it in our function,

Let's refer jquery file and create a method call when save button clicks as below, in here it has stop executing save action method in students controller.


<script  src="~/lib/jquery/dist/jquery.js"></script>
<script>
    $(function () {
        $('#btnSave').click(function (e) {
            e.preventDefault();
        });
    });
</script>

Add a confirm dialog template as below,


<div  id="confirmDialog" title="Save Student" hidden>
    <p>Do you want to save changes </p>
</div>

Let's give edit form an id and initialize confirm dialog as below,

we haven't added jquery ui in edit view, let's add it, open bower.json file and add jquery-ui library

If you navigate to lib folder, you can see jquery-ui is installed

Let's refer jquery-ui in _layout view, run the application and see any errors are available in console tab


 <script  src="~/lib/jquery-ui/jquery-ui.js"></script>

Let's call confirmation dialog when hit on save button,

Run the application and click on save button, it shows confirmation dialog as follows, it doesn't have any styling so let's style it a bit

Add jquery-ui css file in layout page and it will take care about styling of the confirmation dialog box

Save layout page and refresh edit view, it shows confirmation box as follows, When you click on cancel button, dialog box closes. when you click on ok button, it submits the edit form and hit on Edit action result

↑ Return to Top

5 Show a confirmation box when an assignment deletes

Create assignment model as follows,


 public class  Assignment
    {
 
        public int  Id { get; set; }
 
        public string  Assignment { get; set; }
 
        public int  Subject { get; set; }
 
        public int  StudentId { get; set; }
 
        public virtual  Student Student  { get; set; }
 
    }

Add assignments model to db context as below,


 public DbSet<Assignment> Assignments {  get; set; }

Let's add migrations and update database like this, it will create assignment table in the database,
You don't need to run migrations every time you make a change into database, set automaticmigrations to true , then it will apply database changes when application builds

Add Assignments controller like this, It will create AssignmentsController with all CRUD operations and views

Create assignments as below, It's going to show a drop down with student ids, lets leave it as it is, If you want you can list down student names

Add few assignments like this,

Let's change Student detail view a bit, we want to show assignments each user has submitted,
We have to create a StudentViewModel to display all assignments user has submitted

 
 public class  StudentViewModel
   {
 
       public int  Id { get; set; }
 
       public string  Name { get; set; }
 
       public int  Age { get; set; }
 
       public List<Course> Courses { get; set; }
 
   }

Change Student details method like this, return StudentViewModel object to Details view with List of assignments student has submitted


StudentViewModel studentViewModel = new StudentViewModel();
studentViewModel.Id = student.Id;
studentViewModel.Name = student.Name;
studentViewModel.Age = student.Age;
studentViewModel.Year = student.Year;
 
List<Assignment> assignments = _context.Assignments.Where(a => a.StudentId == id).ToList();
studentViewModel.Assignments = assignments;
 
return View(studentViewModel);

Pass Studentviewmodel in details view and display student assignments as below,
Create a table for assignments and create an action link to delete an assignment student has submitted


 <div>
    <h4>Student</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Age)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Age)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.Year)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Year)
        </dd>
    </dl>
    <table class="table">
        <thead>
            <tr>
                <th style="display:none">
 
                </th>
                <th>
                    @Html.Display("Title")
                </th>
                <th>
                    @Html.Display("Subject")
                </th>
                <th>
 
                </th>
            </tr>
        </thead>
        @foreach (var item in Model.Assignments)
        {
            <tr>
                <td style="display:none">
                    @Html.HiddenFor(modelItem => item.Id)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Title)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Subject)
                </td>
                <td id="@item.Id">
                    @Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { @id = "btnDelete" })
                </td>
            </tr>
 
        }
    </table>
</div>
<div>
    <a asp-action="Edit" asp-route-id="@Model.Id">Edit</a> |
    <a asp-action="Index">Back to List</a>
</div>

Add confirm dialog box template and jquery library as below,


<div  id="confirmDialog" title="Remove Assignment" hidden>
    <p>Do you want to save changes </p>
</div>

It's bit different how we handle delete button click in a list, $('a[id*=btnDelete]') jquery selector get <a> tag with id btnDelete,
Its not straightforward to get id of an assignment you want to delete,
When we delete a student we passed model ID , but in this example we need to get row id, when it clicks delete link, it retrieves id of the clicked row,
we clicked on delete link that means a td element in a row,
$(this).parent()[0].id is selecting the parent of that td element, that means clicked row id
We can pass a parameter to the confirm dialog by appending data property in a dialog box, $('#confirmDialog').data('id', id)
When click on OK button in the confirm dialog, it hit on Assignment delete action method.


<script  src="~/lib/jquery/dist/jquery.js"></script>
<script>
    $(function () {
 
        $('a[id*=btnDelete]').click(function (e) {
            debugger;
            e.preventDefault();
            var id = $(this).parent()[0].id;
            $('#confirmDialog').data('id', id).dialog('open');
        });
 
        $("#confirmDialog").dialog({
            autoOpen: false,
            modal: true,
            resizable: false,
            buttons: {
                "Ok": function () {
                    var id = $(this).data("id");
                    window.location.href = '/Assignments/Delete/' + id;
                },
                "Cancel": function (e) {
                    $(this).dialog("close");
                }
            },
        });
    });
</script>

Run application and see how it works,

↑ Return to Top

6 Download

Install front end libraries like Jquery, Jquery-ui using bower,

Go to solution explorer and open cmd from there, install bower packages as below, you have to navigate to the path where bower.json file is available

↑ Return to Top

You can download source code from here, https://gallery.technet.microsoft.com/Jquery-dialog-fb83c55d

↑ Return to Top

6.2 GitHub

You can clone this git hub repo and check the code, https://github.com/hansamaligamage/jquerydialog

↑ Return to Top

7 Conclusion

Article has explained how to show a confirmation dialog when a button clicks in a grid view cell and as well as a single button in a view, We could implement this functionality using jquery selectors and jquery ui dialog box

↑ Return to Top

8 See Also

↑ Return to Top

9 References

↑ Return to Top