ASP.NET Core : Advanced JQuery dialog actions
1 Introduction
This article explains how to use same JQuery confirmation dialog box when different actions performs in a page. It focuses on how to pass multiple parameters into JQuery dialog box and process different actions based on that. This demonstration creates a web application in ASP.NET Core using Visual Studio 2017, Let's dive deeper and read bit more about JQuery dialog features.
2 Background
- Check this article on basic JQuery dialog, https://social.technet.microsoft.com/wiki/contents/articles/37986.asp-net-core-how-to-show-a-confirmation-dialog-with-jquery.aspx
- If you want to know how to create a Web API application in .NET Core, check this article https://social.technet.microsoft.com/wiki/contents/articles/36340.asp-netcore-create-a-web-api-application.aspx
- Learn how to secure a .NET Core web application with Identity Server 4, https://social.technet.microsoft.com/wiki/contents/articles/37169.secure-your-netcore-web-applications-using-identityserver-4.aspx
- Check this article if you want to secure a web application using ASP.NET Identity, with less coding https://social.technet.microsoft.com/wiki/contents/articles/37797.asp-net-identity-customize-user-authentication.aspx
- Say Hello! to .NET Core in a Linux server, https://social.technet.microsoft.com/wiki/contents/articles/36330.net-core-with-a-linux-server-hello-world.aspx
- If you are curious to know how to install .NET Core in a Linux server, go through this article, https://social.technet.microsoft.com/wiki/contents/articles/36318.install-netcore-in-a-linux-server.aspx
- Check this article to know how to create a web application in .NET Core on top of a Linux server, https://social.technet.microsoft.com/wiki/contents/articles/36333.create-a-web-application-in-netcore-with-a-linux-server.aspx
- If you are interested to know how to use a template generator like Yeoman to create a web application template, please go through this article, https://social.technet.microsoft.com/wiki/contents/articles/36334.net-core-create-web-application-with-yeoman-template-generator.aspx
3 Create a Web application
Create a web application using Visual Studio 2017, Select ASP.NET Core Web application from C# category
Select Empty application from *ASP.NET Core templates
Add landing page as index.html in wwwroot folder
Run the application and see what happens, it still shows Hello World! shows from Startup class, Let's try to set index.html file as startup page
Add header tag in index page
Let's change index.html page like this, Now project loads index.html page as startup page
Let's create a course web page, it displays list of modules each course has and multiple images and videos relevant to course. When try to remove a module or an image it shows a JQuery confirmation dialog, Let's see how we can show same JQuery dialog popup for all these scenarios (for a list of modules, set of images and videos)
4 Create Course web page
First of all, let's install ASP.NET Core MVC into the application, Go to Nuget Package Manager explorer and search for ASP.NET Core MVC and install mvc libraries
4.1 Create Home Controller
Create Controllers folder and add a controller, Fill Index method as follows, it's going to print below text in browser window, action method route is defined using Route attribute, When you navigate to /home it will show this text.
Run the application and navigate to home, You can view page as follows
4.2 Create a View
Create Views folder in project root directory, create index view inside Views/Home folder,
Run the application and see what it shows, navigate to home path, it shows empty page as below.
4.3 Create CourseViewModel
Create View Models folder in project root folder, add Courseviewmodel into it. Add list of modules. images and videos as below. I created Module class inside Course class, since Course contains list of Modules
public class Course
{
public int Id { get; set; }
public string CourseTitle { get; set; }
public List<Module> Modules { get; set; }
public List<string> CourseImageUrls { get; set; }
public List<string> CourseVideoUrls { get; set; }
}
public class Module
{
public int Id { get; set; }
public string Title { get; set; }
public string Level { get; set; }
public string Lecturer { get; set; }
}
Go to HomeController and populate courseviewmodel as follows, change Route attribute in Index action method
public class HomeController : Controller
{
// GET: /<controller>/
[Route("/")]
public IActionResult Index()
{
List<Module> modules = new List<Module>() { new Module {Id = 1, Title = "Frontiers of Physics", Level = "Beginner", Lecturer = "Simon De Silva" },
new Module { Id = 2, Title = "Quantum Physics", Level = "Beginner", Lecturer = "Simon De Silva" },
new Module { Id = 3, Title = "Mathematics for Physicists", Level = "Advanced", Lecturer = "Ryan Perera" } };
List<string> imageUrls = new List<string>() { "http://physicslocker.com/physicslocker/images/physics.jpg",
"http://physics.uconn.edu/wp-content/uploads/sites/1363/2015/08/physics.png",
"http://www.aplusphysics.com/assets/images/slide05.png" };
List<string> videoUrls = new List<string>() { "https://www.youtube.com/embed/DxQK1WDYI_k",
"https://www.youtube.com/embed/4xSPlQUejd8" };
Course course = new Course() { Id = 1, CourseTitle = "Physics", Modules = modules, CourseImageUrls = imageUrls, CourseVideoUrls = videoUrls };
return View(course);
}
}
4.4 Change Course view
Add Course view model in Index page and show all course properties as below, show course information along with module list
@model jqueryconfirmdialog.ViewModels.Course
<div>
@Html.HiddenFor(model => model.Id)
Course: @Html.DisplayFor(model => model.CourseTitle)
</div>
<br/>
<table>
<thead>
<tr>
<th style="display:none">
</th>
<th>
@Html.DisplayName("Module")
</th>
<th>
@Html.DisplayName("Lecturer")
</th>
<th>
@Html.DisplayName("Level")
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach(var item in Model.Modules)
{
<tr>
<td style="display:none">
@Html.HiddenFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Lecturer)
</td>
<td>
@Html.DisplayFor(modelItem => item.Level)
</td>
<td id="@item.Id">
@Html.ActionLink("Remove", "Delete", new { id = item.Id }, new { @id = "btnRemove" })
</td>
</tr>
}
</tbody>
</table>
<br/>
course related images and videos are shown below
<div>
@for (var i = 0; i < Model.CourseImageUrls.Count; i++)
{
if (!string.IsNullOrEmpty(Model.CourseImageUrls[i]))
{
<img id="image_@Model.CourseImageUrls[i]" src="@Url.Content(Model.CourseImageUrls[i])" style="width:200px; height:200px" />
}
<input id="btnImageRemove" type="button" value="Remove" class="btn btn-default" />
}
</div>
<br/>
<div>
@for (var i = 0; i < Model.CourseVideoUrls.Count; i++)
{
if (!string.IsNullOrEmpty(Model.CourseVideoUrls[i]))
{
<object width="320" height="240" data="@Url.Content(Model.CourseVideoUrls[i])"></object>
}
<input id="btnVideoRemove" type="button" value="Remove" class="btn btn-default" />
}
</div>
Run your application and see what it shows, It shows course name, list of available modules, images and videos related to course
4.5 Create JQuery dialog
Let's try to show a confirmation dialog box when you want to delete a module, when deleting an image or video, for all these 3 actions need to use same JQuery dialog box, Let's see how we can achieve that.
When document loads, write JQuery method to show delete module click event, select remove link in modules list and try to show confirm dialog box, When calling confirm dialog box it assign two parameters as type and module, When we set parameters in click event, we can extract them in dialog box initialization
<script>
$(function () {
debugger;
$('a[id*=btnRemove]').click(function (e) {
debugger;
e.preventDefault();
var id = $(this).parent()[0].id;
var data = $('#confirmDialog').data();
data.type = 1;
data.module = id;
$('#confirmDialog').dialog('open');
});
});
</script>
When we run this application, it says JQuery and JQuery ui are not defined, let's add those external script libraries into course web page. In this example it has added min version of Jquery & Jquery-ui
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.11.4/jquery-ui.min.js"></script>
create confirm dialog box as below,
<div id="confirmDialog" title="Save changes" hidden>
<p>Do you want to save changes </p>
</div>
Run your application and click on Remove link, it shows error page as below, It says confirm dialog initialization has not happened, we have to initialize the confirm dialog box before open it
Let's initialize confirmation dialog box as follows, we'll implement OK button later in this example
$("#confirmDialog").dialog({
autoOpen: false,
modal: true,
resizable: false,
buttons: {
"Ok": function () {
},
"Cancel": function (e) {
$(this).dialog("close");
}
},
});
Run your application and check whether confirmation dialog box shows,
JQuery dialog shows as above, let's add some css changes and style this a bit, Add references to Jquery and Jquery-ui style files
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.css"/>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
run your application and see how it shows,
4.6 Implement Jquery dialog actions
Let's fill OK button click when removing a module from list,
If you remember when module Remove link is clicked, we passed type as 1 and selected module id,
In OK button click of jquery dialog, we can extract that as below
$("#confirmDialog").dialog({
autoOpen: false,
modal: true,
resizable: false,
buttons: {
"Ok": function () {
var type = $(this).data('type');
var module = $(this).data('module');
if(type == 1)
window.location.href = '/Home/RemoveModule?id=' + module;
},
"Cancel": function (e) {
$(this).dialog("close");
}
},
});
Let's implement controller action method to delete a module
public IActionResult RemoveModule(int id)
{
Module module = modules.Find(p => p.Id == id);
if(module != null)
modules.Remove(module);
Course course = new Course() { Id = 1, CourseTitle = "Physics", Modules = modules, CourseImageUrls = imageUrls,
CourseVideoUrls = videoUrls };
return View("Index", course);
}
We haven't added routing options to this application, let's add default routing, then it will redirect to list of modules page with new list,
Go to Startup class, in Configure method add default routing to handle request urls.
app.UseMvc(routes => routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"));
Run your application, delete a module and check whether it works,
Let's try to remove an image/video from a course,
Let's take image type as 1 and video type as 2. we have to pass type of resource and specific resource is getting deleted.
Let's create Resource class to hold Image and Video information
public class Resource
{
public int Id { get; set; }
public string Url { get; set; }
}
We had to change modules list used to display the grid as follows,
private List<Module> modules = new List<Module>() { new Module {Id = 1, Title = "Frontiers of Physics", Level = "Beginner",
Lecturer = "Simon De Silva" },
new Module { Id = 2, Title = "Quantum Physics", Level = "Beginner",
Lecturer = "Simon De Silva" },
new Module { Id = 3, Title = "Mathematics for Physicists", Level = "Advanced",
Lecturer = "Ryan Perera" } };
List<Resource> imageUrls = new List<Resource>() { new Resource { Id = 1,
Url = "http://physicslocker.com/physicslocker/images/physics.jpg" },
new Resource { Id = 2,
Url = "http://physics.uconn.edu/wp-content/uploads/sites/1363/2015/08/physics.png" }, new Resource { Id = 3,
Url = "http://www.aplusphysics.com/assets/images/slide05.png" } };
List<Resource> videoUrls = new List<Resource>() { new Resource { Id = 1, Url = "https://www.youtube.com/embed/DxQK1WDYI_k" },
new Resource { Id = 2, Url = "https://www.youtube.com/embed/4xSPlQUejd8" } };
Let's add image remove button click implementation,
using JQuery selector ('input[id*=btnImageRemove]') we can track remove link click, then get id attribute of selected parent element as follows,
$('input[id*=btnImageRemove]').click(function () {
var id = $(this).parent()[0].id;
var data = $('#confirmDialog').data();
data.type = 2;
data.id = id;
$('#confirmDialog').dialog('open');
});
as same as image remove link, let's add video remove link
$('input[id*=btnVideoRemove]').click(function () {
var id = $(this).parent()[0].id;
var data = $('#confirmDialog').data();
data.type = 3;
data.id = id;
$('#confirmDialog').dialog('open');
});
When click on OK button in confirm dialog box, it checks type of event, according to type it removes a module, image or video
$("#confirmDialog").dialog({
autoOpen: false,
modal: true,
resizable: false,
buttons: {
"Ok": function () {
var type = $(this).data('type');
if (type == 1) { // remove a module
var module = $(this).data('module');
window.location.href = '/Home/RemoveModule?id=' + module;
}
else // remove an image or video
{
var id = $(this).data('id');
window.location.href = '/Home/RemoveResource?id=' + id + '&type=' + type;
}
},
"Cancel": function (e) {
$(this).dialog("close"); }
}
});
Now let's see how to implement controller function to remove an image or video
public IActionResult RemoveResource(int id, int type)
{
if (type == 2) //image
{
Resource resource = imageUrls.Find(p => p.Id == id);
if (resource != null)
imageUrls.Remove(resource);
}
else if (type == 3) //videos
{
Resource resource = videoUrls.Find(p => p.Id == id);
if (resource != null)
videoUrls.Remove(resource);
}
Course course = new Course() { Id = 1, CourseTitle = "Physics", Modules = modules, CourseImageUrls = imageUrls, CourseVideoUrls = videoUrls };
return View("Index", course);
}
Let's run this application and check whether it works,
We are showing a course entity along with list of modules, image and video resources.
This example hasn't used any storage to store this course entity, it simply uses a course object.
5 Download
5.1 Tech Net Gallery
download sample source code from tech net gallery, https://gallery.technet.microsoft.com/ASPNET-Core-Advanced-e11baa3d?redir=0
5.2 GitHub
You can clone sample application from git hub repository, https://github.com/hansamaligamage/advancedjquerydialog
6 Conclusion
This article has demonstrated how to show a confirmation dialog box using JQuery in a ASP.NET Core view, and it has used MVC architecture to display this view.
In this example it has highlighted how to show multiple confirm dialog boxes in various actions, but using only a div tag.
In OK button implementation in this confirm dialog box, it checks type of the action performed and process necessary steps. Also in this example it has showed how to use multiple parameters in a jquery dialog box
7 See Also
- ASP.NET Core : How to show a confirmation dialog with jquery
- ASP.NETCore: Create a Web API application
- Secure your .NETCore web applications using IdentityServer 4
- ASP.NET Identity: Customize User Authentication
- .NET Core with a Linux server: Hello World!
- Install .NETCore in a Linux server
- Create a web application in.NETCore with a Linux server
- .NET Core: Create web application with Yeoman template generator