Building Web Application Using Entity Framework and MVC 5: Part Three

Here I’m going to talk about how to perform Fetch, Edit, Update and Delete (FEUD) operations in our application.

This is Part 3 of the series on Building Web Applications in ASP.NET MVC 5. In Part 1, you've learned about creating a simple database from scratch using Microsoft SQL Server, a brief overview about ASP.NET MVC in general, creating a data access using the Entity Framework Database First approach and a simple implementation of a Signup page in MVC . Part 2 of the series talks about the step-by-step process on creating a basic login page and creating a simple role-based page authorization within the MVC application. If you haven't gone through my previous articles then you can refer to the following links:

This article shows how to do Fetch, Edit, Update and Delete (FEUD) operations in our application. The idea is to create a maintenance page where admin users can modify user profiles. There are many possible ways to implement FEUD operations in MVC depending on your business needs. For this specific demo, I'm going to use jQuery and jQuery AJAX to do asynchronous operations in our page.

Let's get started!

Fetching and Displaying the Data

For this example, I'm going to create a partial view for displaying the list of users from the database. Partial views allow you to define a view that will be rendered inside a main view. If you have used WebForms before then you can think of partial views as user controls (.ascx).

Step 1: Adding the View Models

The first thing we need is to create view models for our view. Add the following code within the “UserModel.cs” class:

  1. public class UserProfileView  
  2.     {  
  3.         [Key]  
  4.         public int SYSUserID { getset; }  
  5.         public int LOOKUPRoleID { getset; }  
  6.         public string RoleName { getset; }  
  7.         public bool? IsRoleActive { getset; }  
  8.         [Required(ErrorMessage = "*")]  
  9.         [Display(Name = "Login ID")]  
  10.         public string LoginName { getset; }  
  11.         [Required(ErrorMessage = "*")]  
  12.         [Display(Name = "Password")]  
  13.         public string Password { getset; }  
  14.         [Required(ErrorMessage = "*")]  
  15.         [Display(Name = "First Name")]  
  16.         public string FirstName { getset; }  
  17.         [Required(ErrorMessage = "*")]  
  18.         [Display(Name = "Last Name")]  
  19.         public string LastName { getset; }  
  20.         public string Gender { getset; }  
  21.     }  
  22.   
  23.     public class LOOKUPAvailableRole  
  24.     {  
  25.         [Key]  
  26.         public int LOOKUPRoleID { getset; }  
  27.         public string RoleName { getset; }  
  28.         public string RoleDescription { getset; }  
  29.     }  
  30.   
  31.     public class Gender  
  32.     {  
  33.         public string Text { getset; }  
  34.         public string Value { getset; }  
  35.     }  
  36.     public class UserRoles  
  37.     {  
  38.         public int? SelectedRoleID { getset; }  
  39.         public IEnumerable<LOOKUPAvailableRole> UserRoleList { getset; }  
  40.     }  
  41.   
  42.     public class UserGender  
  43.     {  
  44.         public string SelectedGender { getset; }  
  45.         public IEnumerable<Gender> Gender { getset; }  
  46.     }  
  47.     public class UserDataView  
  48.     {  
  49.         public IEnumerable<UserProfileView> UserProfile { getset; }  
  50.         public UserRoles UserRoles { getset; }  
  51.         public UserGender UserGender { getset; }  
  52.     } 

If you still remember, view models are models that house some properties that we only need for the view or page.

Step 2: Adding the ManageUserPartial view

Open the “UserManager” class and declare the namespace below:

  1. using System.Collections.Generic; 

The namespace above contains interfaces and classes that define generic collections that allow us to create strongly-typed collections. Now add the following code to the “UserManager” class:

  1. public List < LOOKUPAvailableRole > GetAllRoles() {  
  2.     using(DemoDBEntities db = new DemoDBEntities()) {  
  3.         var roles = db.LOOKUPRoles.Select(o = > new LOOKUPAvailableRole {  
  4.             LOOKUPRoleID = o.LOOKUPRoleID,  
  5.             RoleName = o.RoleName,  
  6.             RoleDescription = o.RoleDescription  
  7.         }).ToList();  
  8.   
  9.         return roles;  
  10.     }  
  11. }  
  12.   
  13. public int GetUserID(string loginName) {  
  14.     using(DemoDBEntities db = new DemoDBEntities()) {  
  15.         var user = db.SYSUsers.Where(o = > o.LoginName.Equals(loginName));  
  16.         if (user.Any()) return user.FirstOrDefault().SYSUserID;  
  17.     }  
  18.     return 0;  
  19. }  
  20. public List < UserProfileView > GetAllUserProfiles() {  
  21.     List < UserProfileView > profiles = new List < UserProfileView > ();  
  22.     using(DemoDBEntities db = new DemoDBEntities()) {  
  23.         UserProfileView UPV;  
  24.         var users = db.SYSUsers.ToList();  
  25.   
  26.         foreach(SYSUser u in db.SYSUsers) {  
  27.             UPV = new UserProfileView();  
  28.             UPV.SYSUserID = u.SYSUserID;  
  29.             UPV.LoginName = u.LoginName;  
  30.             UPV.Password = u.PasswordEncryptedText;  
  31.   
  32.             var SUP = db.SYSUserProfiles.Find(u.SYSUserID);  
  33.             if (SUP != null) {  
  34.                 UPV.FirstName = SUP.FirstName;  
  35.                 UPV.LastName = SUP.LastName;  
  36.                 UPV.Gender = SUP.Gender;  
  37.             }  
  38.   
  39.             var SUR = db.SYSUserRoles.Where(o = > o.SYSUserID.Equals(u.SYSUserID));  
  40.             if (SUR.Any()) {  
  41.                 var userRole = SUR.FirstOrDefault();  
  42.                 UPV.LOOKUPRoleID = userRole.LOOKUPRoleID;  
  43.                 UPV.RoleName = userRole.LOOKUPRole.RoleName;  
  44.                 UPV.IsRoleActive = userRole.IsActive;  
  45.             }  
  46.   
  47.             profiles.Add(UPV);  
  48.         }  
  49.     }  
  50.   
  51.     return profiles;  
  52. }  
  53.   
  54. public UserDataView GetUserDataView(string loginName) {  
  55.     UserDataView UDV = new UserDataView();  
  56.     List < UserProfileView > profiles = GetAllUserProfiles();  
  57.     List < LOOKUPAvailableRole > roles = GetAllRoles();  
  58.   
  59.     int ? userAssignedRoleID = 0, userID = 0;  
  60.     string userGender = string.Empty;  
  61.   
  62.     userID = GetUserID(loginName);  
  63.     using(DemoDBEntities db = new DemoDBEntities()) {  
  64.         userAssignedRoleID = db.SYSUserRoles.Where(o = > o.SYSUserID == userID) ? .FirstOrDefault().LOOKUPRoleID;  
  65.         userGender = db.SYSUserProfiles.Where(o = > o.SYSUserID == userID) ? .FirstOrDefault().Gender;  
  66.     }  
  67.   
  68.     List < Gender > genders = new List < Gender > ();  
  69.     genders.Add(new Gender {  
  70.         Text = "Male", Value = "M"  
  71.     });  
  72.     genders.Add(new Gender {  
  73.         Text = "Female", Value = "F"  
  74.     });  
  75.   
  76.     UDV.UserProfile = profiles;  
  77.     UDV.UserRoles = new UserRoles {  
  78.         SelectedRoleID = userAssignedRoleID, UserRoleList = roles  
  79.     };  
  80.     UDV.UserGender = new UserGender {  
  81.         SelectedGender = userGender, Gender = genders  
  82.     };  
  83.     return UDV;  

The methods shown from the code above is pretty much self-explanatory as their method names suggest. The main method there is the GetUserDataView() and what it does is it gets all user profiles and roles. The UserRoles and UserGender properties will be used during the editing and updating of the user data. We will use these values to populate the dropdown lists for roles and gender.

Step 3: Adding the ManageUserPartial action method

Open the “HomeController.cs” class and add the following namespaces:

  1. using System.Web.Security;  
  2. using MVC5RealWorld.Models.ViewModel;  
  3. using MVC5RealWorld.Models.EntityManager; 

And then add the following action method below:

  1. [AuthorizeRoles("Admin")]  
  2. public ActionResult ManageUserPartial() {  
  3.    if (User.Identity.IsAuthenticated) {  
  4.       string loginName = User.Identity.Name;  
  5.       UserManager UM = new UserManager();  
  6.       UserDataView UDV = UM.GetUserDataView(loginName);  
  7.       return PartialView(UDV);  
  8.    }  
  9.    return View();  

The code above is decorated with the custom Authorize attribute so that only admin users can invoke that method. What it does is it calls the GetUserDataView() method by passing in the loginName as the parameter and return the result in the partial view.

Step 4: Adding the ManageUserPartial partial view

Now let's create the partial view. Right-click on the ManageUserPartial method and select “Add New” view. This will bring up the following dialog:



Since we will create a custom view for managing the users then just select an “Empty” template and be sure to tick the “Create as a partial view” option. Click Add and then copy the following HTML markup below:

  1. @model MVC5RealWorld.Models.ViewModel.UserDataView  
  2.   
  3. <div>  
  4.     <h1>List of Users</h1>  
  5.     <table class="table table-striped table-condensed table-hover">  
  6.         <thead>  
  7.             <tr>  
  8.                 <th>ID</th>  
  9.                 <th>Login ID</th>  
  10.                 <th>Password</th>  
  11.                 <th>First Name</th>  
  12.                 <th>Last Name</th>  
  13.                 <th>Gender</th>  
  14.                 <th colspan="2">Role</th>  
  15.                 <th></th>  
  16.                 <th></th>  
  17.             </tr>  
  18.         </thead>  
  19.         <tbody>  
  20.             @foreach (var i in Model.UserProfile) {  
  21.                 <tr>  
  22.                     <td> @Html.DisplayFor(m => i.SYSUserID)</td>  
  23.                     <td> @Html.DisplayFor(m => i.LoginName)</td>  
  24.                     <td> @Html.DisplayFor(m => i.Password)</td>  
  25.                     <td> @Html.DisplayFor(m => i.FirstName)</td>  
  26.                     <td> @Html.DisplayFor(m => i.LastName)</td>  
  27.                     <td> @Html.DisplayFor(m => i.Gender)</td>  
  28.                     <td> @Html.DisplayFor(m => i.RoleName)</td>  
  29.                     <td> @Html.HiddenFor(m => i.LOOKUPRoleID)</td>  
  30.                     <td><a href="javacript:void(0)" class="lnkEdit">Edit</a></td>  
  31.                     <td><a href="javacript:void(0)" class="lnkDelete">Delete</a></td>  
  32.                 </tr>  
  33.             }  
  34.         </tbody>  
  35.     </table>  
  36. </div> 

Now open the “AdminOnly.cshtml” view and add the following markup:

  1. <div id="divUserListContainer">  
  2.     @Html.Action("ManageUserPartial", "Home");  
  3. </div> 

Step 5: Running the page

Now try to login to your web page then navigate to: http://localhost:15599/Home/AdminOnly. The output should look something like this:



Pretty easy, right? Now let's move to the next step.

Editing and Updating the Data

Since we will use jQueryUI for providing a dialog box for the user to edit the data then we need to add a reference to it first. To do that, just right-click on your project and then select Manage Nuget Packages. In the search box type in “jquery” and select “jQuery.UI.Combined” as shown in the image below:



Once installed the jQueryUI library should be added to your project under the “Script” folder:



Step 1

Now go to Views > Shared >_Layout.cshtml and add the jQueryUI reference in the following order:

  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script>    
  2. <script src="~/Scripts/jquery-ui-1.11.4.min.js"></script>    
  3. <script src="~/Scripts/bootstrap.min.js"></script> 
The jQueryUI should be added after the jQuery since jQueryUI uses the core jQuery library under the hood.

Now add the jQueryUI CSS reference as in the following:

  1. <link href="~/Content/themes/base/all.css" rel="stylesheet" />   

Step 2

Now to add the UpdateUserAccount() method.

Keep in mind that this demo is intended to make an app as simple as possible. In complex real scenarios I strongly suggest you use a Repository pattern and Unit-of-Work for your data access layer.

Add the following code within the “UserManager.cs” class:

  1. public void UpdateUserAccount(UserProfileView user) {  
  2.   
  3.     using(DemoDBEntities db = new DemoDBEntities()) {  
  4.         using(var dbContextTransaction = db.Database.BeginTransaction()) {  
  5.             try {  
  6.   
  7.                 SYSUser SU = db.SYSUsers.Find(user.SYSUserID);  
  8.                 SU.LoginName = user.LoginName;  
  9.                 SU.PasswordEncryptedText = user.Password;  
  10.                 SU.RowCreatedSYSUserID = user.SYSUserID;  
  11.                 SU.RowModifiedSYSUserID = user.SYSUserID;  
  12.                 SU.RowCreatedDateTime = DateTime.Now;  
  13.                 SU.RowMOdifiedDateTime = DateTime.Now;  
  14.   
  15.                 db.SaveChanges();  
  16.   
  17.                 var userProfile = db.SYSUserProfiles.Where(o = > o.SYSUserID == user.SYSUserID);  
  18.                 if (userProfile.Any()) {  
  19.                     SYSUserProfile SUP = userProfile.FirstOrDefault();  
  20.                     SUP.SYSUserID = SU.SYSUserID;  
  21.                     SUP.FirstName = user.FirstName;  
  22.                     SUP.LastName = user.LastName;  
  23.                     SUP.Gender = user.Gender;  
  24.                     SUP.RowCreatedSYSUserID = user.SYSUserID;  
  25.                     SUP.RowModifiedSYSUserID = user.SYSUserID;  
  26.                     SUP.RowCreatedDateTime = DateTime.Now;  
  27.                     SUP.RowModifiedDateTime = DateTime.Now;  
  28.   
  29.                     db.SaveChanges();  
  30.                 }  
  31.   
  32.                 if (user.LOOKUPRoleID > 0) {  
  33.                     var userRole = db.SYSUserRoles.Where(o = > o.SYSUserID == user.SYSUserID);  
  34.                     SYSUserRole SUR = null;  
  35.                     if (userRole.Any()) {  
  36.                         SUR = userRole.FirstOrDefault();  
  37.                         SUR.LOOKUPRoleID = user.LOOKUPRoleID;  
  38.                         SUR.SYSUserID = user.SYSUserID;  
  39.                         SUR.IsActive = true;  
  40.                         SUR.RowCreatedSYSUserID = user.SYSUserID;  
  41.                         SUR.RowModifiedSYSUserID = user.SYSUserID;  
  42.                         SUR.RowCreatedDateTime = DateTime.Now;  
  43.                         SUR.RowModifiedDateTime = DateTime.Now;  
  44.                     } else {  
  45.                         SUR = new SYSUserRole();  
  46.                         SUR.LOOKUPRoleID = user.LOOKUPRoleID;  
  47.                         SUR.SYSUserID = user.SYSUserID;  
  48.                         SUR.IsActive = true;  
  49.                         SUR.RowCreatedSYSUserID = user.SYSUserID;  
  50.                         SUR.RowModifiedSYSUserID = user.SYSUserID;  
  51.                         SUR.RowCreatedDateTime = DateTime.Now;  
  52.                         SUR.RowModifiedDateTime = DateTime.Now;  
  53.                         db.SYSUserRoles.Add(SUR);  
  54.                     }  
  55.   
  56.                     db.SaveChanges();  
  57.                 }  
  58.                 dbContextTransaction.Commit();  
  59.             } catch {  
  60.                 dbContextTransaction.Rollback();  
  61.             }  
  62.         }  
  63.     }  

The method above takes a UserProfileView object as the parameter. This parameter object is coming from a strongly-type view. What it does is it first issues a query to the database using the LINQ syntax to get the specific user data by passing the SYSUserID. It then updates the SYSUser object with the corresponding data from the UserProfileView object. The second query gets the associated SYSUserProfiles data and then updates the corresponding values. Then it then looks for the associated LOOKUPRoleID for a certain user. If the user doesn't have a role assigned to them then it adds a new record to the database otherwise just update the table.

If you also notice, I used a simple transaction within that method. This is because the tables SYSUser, SYSUserProfile and SYSUserRole are pretty much related to each other and we need to be sure that we only commit changes to the database if the operation for each table is successful. The Database.BeginTransaction() is only available in EF 6 onwards.

Step 3

Now to add the UpdateUserData Action Method.

Add the following code within the “HomeController” class:

  1. [AuthorizeRoles("Admin")]  
  2. public ActionResult UpdateUserData(int userID, string loginName, string password, 
    string
     firstName, string lastName, string gender, int roleID = 0) {  
  3.     UserProfileView UPV = new UserProfileView();  
  4.     UPV.SYSUserID = userID;  
  5.     UPV.LoginName = loginName;  
  6.     UPV.Password = password;  
  7.     UPV.FirstName = firstName;  
  8.     UPV.LastName = lastName;  
  9.     UPV.Gender = gender;  
  10.   
  11.     if (roleID > 0)  
  12.       UPV.LOOKUPRoleID = roleID;  
  13.   
  14.       UserManager UM = new UserManager();  
  15.       UM.UpdateUserAccount(UPV);  
  16.   
  17.       return Json(new { success = true });  

The method above is responsible for collecting data that is sent from the view for update. It then calls the method UpdateUserAccount() and passes the UserProfileView model view as the parameter. The UpdateUserData method will be called using an AJAX request.

Step 4

Now to modify the UserManagePartial view.

Add the following HTML markup within UserManagePartial.cshtml:

  1. <div id="divEdit" style="display:none">  
  2.     <input type="hidden" id="hidID" />  
  3.     <table>  
  4.         <tr>  
  5.             <td>Login Name</td>  
  6.             <td>  
  7.                 <input type="text" id="txtLoginName" class="form-control" />  
  8.             </td>  
  9.         </tr>  
  10.         <tr>  
  11.             <td>Password</td>  
  12.             <td>  
  13.                 <input type="text" id="txtPassword" class="form-control" />  
  14.             </td>  
  15.         </tr>  
  16.         <tr>  
  17.             <td>First Name</td>  
  18.             <td>  
  19.                 <input type="text" id="txtFirstName" class="form-control" />  
  20.             </td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td>Last Name</td>  
  24.             <td>  
  25.                 <input type="text" id="txtLastName" class="form-control" />  
  26.             </td>  
  27.         </tr>  
  28.         <tr>  
  29.             <td>Gender</td>  
  30.             <td>@Html.DropDownListFor(o => o.UserGender.SelectedGender,  
  31.                        new SelectList(Model.UserGender.Gender, "Value", "Text"),  
  32.                        "",  
  33.                        new { id = "ddlGender", @class="form-control" })  
  34.                 </td>  
  35.         </tr>  
  36.         <tr>  
  37.             <td>Role</td>  
  38.             <td>@Html.DropDownListFor(o => o.UserRoles.SelectedRoleID,   
  39.                        new SelectList(Model.UserRoles.UserRoleList, "LOOKUPRoleID", "RoleName"),   
  40.                        "",   
  41.                        new { id = "ddlRoles", @class="form-control" })  
  42.                 </td>  
  43.         </tr>  
  44.     </table>  
  45. </div> 

Step 5

Now to add the integrate jQuery and jQuery AJAX.

Before we go to the implementation it's important to understand what these technologies are.

  • jQuery is a light weight and feature-rich JavaScript library that enables DOM manipulation, event handling, animation and Ajax much simpler with powerful API that works across all major browsers.
  • jQueryUi provides a set of UI interactions, effects, widgets and themes built on top of the jQuery library.
  • jQuery AJAX enables you to use functions and methods to communicate with your data from the server and loads your data to the client/browser.

Now switch back to the “UserManagePartial” view and add the following script block at the very bottom:

  1. <script type="text/javascript">    
  2.     $(function () {    
  3.     
  4.         var initDialog = function (type) {    
  5.             var title = type;    
  6.             $("#divEdit").dialog({    
  7.                 autoOpen: false,    
  8.                 modal: true,    
  9.                 title: type + ' User',    
  10.                 width: 360,    
  11.                 buttons: {    
  12.                     Save: function () {    
  13.                         var id = $("#hidID").val();    
  14.                         var role = $("#ddlRoles").val();    
  15.                         var loginName = $("#txtLoginName").val();    
  16.                         var loginPass = $("#txtPassword").val();    
  17.                         var fName = $("#txtFirstName").val();    
  18.                         var lName = $("#txtLastName").val();    
  19.                         var gender = $("#ddlGender").val();    
  20.     
  21.                         UpdateUser(id, loginName, loginPass, fName, lName, gender, role);    
  22.                         $(this).dialog("destroy");    
  23.                     },    
  24.                     Cancel: function () { $(this).dialog("destroy"); }    
  25.                 }    
  26.             });    
  27.         }    
  28.     
  29.         function UpdateUser(id, logName, logPass, fName, lName, gender, role) {    
  30.             $.ajax({    
  31.                 type: "POST",    
  32.                 url: "@(Url.Action("UpdateUserData","Home"))",    
  33.                 data: { userID: id, loginName: logName, password: logPass, firstName: fName, lastName: lName, gender: gender, roleID: role },    
  34.                 success: function (data) {    
  35.                     $("#divUserListContainer").load("@(Url.Action("ManageUserPartial","Home", new { status ="update" }))");    
  36.                 },    
  37.                 error: function (error) {    
  38.                     //to do:    
  39.                 }    
  40.             });    
  41.         }    
  42.     
  43.         $("a.lnkEdit").on("click"function () {    
  44.             initDialog("Edit");    
  45.             $(".alert-success").empty();    
  46.             var row = $(this).closest('tr');    
  47.     
  48.             $("#hidID").val(row.find("td:eq(0)").html().trim());    
  49.             $("#txtLoginName").val(row.find("td:eq(1)").html().trim())    
  50.             $("#txtPassword").val(row.find("td:eq(2)").html().trim())    
  51.             $("#txtFirstName").val(row.find("td:eq(3)").html().trim())    
  52.             $("#txtLastName").val(row.find("td:eq(4)").html().trim())    
  53.             $("#ddlGender").val(row.find("td:eq(5)").html().trim())    
  54.             $("#ddlRoles").val(row.find("td:eq(7) > input").val().trim());    
  55.     
  56.             $("#divEdit").dialog("open");    
  57.             return false;    
  58.         });    
  59.     });    
  60.     
  61. </script>   

The initDialog initializes the jQueryUI dialog by customizing the dialog. We customized it by adding our own Save and Cancel buttons for us to write custom code implemetation for each event. In the Save function we extracted each value from the edit form and passed these values to the UpdateUser() JavaScript function.

The UpdateUser() function issues an AJAX request using jQuery AJAX. The "type" parameter indicates what form method the request requires, in this case we set the type as "POST". The "url" is the path to the controller's method that we created in Step 3. Note that the value of url can be a web service, Web API or anything that host your data. The "data" is where we assign values to the method that requires parameter. If your method in the server doesn't require any parameter then you can leave this as empty "{}". The "success" function is usually used when you do a certain process if the request succeeds. In this case we load the partial view to reflect the changes on the view after we update the data. Keep in mind that we are passing a new parameter to the "ManageUserPartial" action that indicates the status of the request.

The last function is where we open the dialog when the user clicks on the "edit" link from the grid. This is also where we extract the data from the grid using jQuery selectors and populate the dialog fields with the extracted data.

Step 6

Now to add then modify the UserManagePartial action method.

If you remember, we added the new parameter “status” to the UserManagePartial method in our AJAX request so we need to update the method signature to accept a parameter. The new method should now look something like this:

  1. [AuthorizeRoles("Admin")]  
  2. public ActionResult ManageUserPartial(string status = "") {  
  3.     if (User.Identity.IsAuthenticated) {  
  4.         string loginName = User.Identity.Name;  
  5.         UserManager UM = new UserManager();  
  6.         UserDataView UDV = UM.GetUserDataView(loginName);  
  7.   
  8.         string message = string.Empty;  
  9.         if (status.Equals("update")) message = "Update Successful";  
  10.         else if (status.Equals("delete")) message = "Delete Successful";  
  11.   
  12.         ViewBag.Message = message;  
  13.   
  14.         return PartialView(UDV);  
  15.     }  
  16.   
  17.     return RedirectToAction("Index""Home");  

Step 7

Now to add the display the Status result.

If you notice we are creating a message string based on a certain operation and store the result in ViewBag. This is to let the user see if a certain operation succeeds. Now add the following markup within the “ManageUserPartial” view:

  1. <span class="alert-success">@ViewBag.Message</span> 

Step 8

Now to run the page.

Here are the outputs.

After clicking the edit dialog:



Editing the data:



After updating the data:



If you've made it this far then congratulations, you're now ready for the next step. Now down to the last part of this series.

Deleting Data

Step 1

Now to add the DeleteUser method.

Add the following method to the “UserManager” class:

  1. public void DeleteUser(int userID) {  
  2.     using(DemoDBEntities db = new DemoDBEntities()) {  
  3.         using(var dbContextTransaction = db.Database.BeginTransaction()) {  
  4.             try {  
  5.   
  6.                 var SUR = db.SYSUserRoles.Where(o = > o.SYSUserID == userID);  
  7.                 if (SUR.Any()) {  
  8.                     db.SYSUserRoles.Remove(SUR.FirstOrDefault());  
  9.                     db.SaveChanges();  
  10.                 }  
  11.   
  12.                 var SUP = db.SYSUserProfiles.Where(o = > o.SYSUserID == userID);  
  13.                 if (SUP.Any()) {  
  14.                     db.SYSUserProfiles.Remove(SUP.FirstOrDefault());  
  15.                     db.SaveChanges();  
  16.                 }  
  17.   
  18.                 var SU = db.SYSUsers.Where(o = > o.SYSUserID == userID);  
  19.                 if (SU.Any()) {  
  20.                     db.SYSUsers.Remove(SU.FirstOrDefault());  
  21.                     db.SaveChanges();  
  22.                 }  
  23.   
  24.                 dbContextTransaction.Commit();  
  25.             } catch {  
  26.                 dbContextTransaction.Rollback();  
  27.             }  
  28.         }  
  29.     }  

The method above deletes the record for a specific user in the SYSUserRole, SYSUserProfile and SYSUser tables.

Step 2

Now to add the DeleteUser action method.

Add the following code within the “HomeController” class:

  1. [AuthorizeRoles("Admin")]  
  2. public ActionResult DeleteUser(int userID) {  
  3.    UserManager UM = new UserManager();  
  4.    UM.DeleteUser(userID);  
  5.    return Json(new { success = true });  

Step 3

Now to add the integrate jQuery and jQuery AJAX.

Add the following script within the <script> tag in the "UserManagePartial" view:

  1. function DeleteUser(id) {  
  2.     $.ajax({  
  3.         type: "POST",  
  4.         url: "@(Url.Action("  
  5.         DeleteUser ","  
  6.         Home "))",  
  7.         data: {  
  8.             userID: id  
  9.         },  
  10.         success: function(data) {  
  11.             $("#divUserListContainer").load("@(Url.Action("  
  12.             ManageUserPartial ","  
  13.             Home ", new { status ="  
  14.             delete " }))");  
  15.         },  
  16.         error: function(error) {}  
  17.     });  
  18. }  
  19.   
  20. $("a.lnkDelete").on("click"function() {  
  21.     var row = $(this).closest('tr');  
  22.     var id = row.find("td:eq(0)").html().trim();  
  23.     var answer = confirm("You are about to delete this user with ID " + id + " . Continue?");  
  24.     if (answer) DeleteUser(id);  
  25.     return false;  
  26. }); 

Step 4

Now to run the page.

Here are the outputs.

After clicking the delete link:



After deletion:



That's it! I hope you enjoyed and learned something from this series of articles.