Menu

Building Web Application using Entity Framework and MVC 5: Part 3

01 June 2015

This is part 3 of the series on Building Web Application in ASP.NET MVC 5. In Part 1, we’ve learned about creating a simple database from scratch using MS SQL Server, a brief overview about ASP.NET MVC in general, creating a data access using Entity Framework database first approach and a simple implementation of a Signup page. 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 the following links below:

In this article I’m going to talk about how to perform 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 particular demo, I’m going to use jQuery and jQuery AJAX to perform asynchronous operation in our page.

Let’s get started!

Fetching and Displaying 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 are using WebForms before then you can think of partial views as user-controls (.ascx).

STEP 1: Adding View Models

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

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

STEP 2: Adding the ManageUserPartial view

Open "UserManager" class and declare the namespace below:

using System.Collections.Generic;

The namespace above contains interfaces and classes that define generic collections, which allow us to create strongly-typed collections. Now add the following code below within your "UserManager" class:

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 "HomeController" class and add the following namespaces below:

using System.Web.Security;
using MVC5RealWorld.Models.ViewModel;
using MVC5RealWorld.Models.EntityManager;

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 make sure to tick the "Create as a partial view" option. Click Add and then copy the following HTML markup below:

STEP 5: Running the page

Editing and Updating Data

Since we are going to 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 in your project under the "Script" folder:

STEP 1: Referencing jQueryUI

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

The jQueryUI should be added after the jQuery since jQueryUI uses the core jQuery library under the hood.

Now add the jQueryUI CSS reference:

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

STEP 2: Adding the UpdateUserAccount() method

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

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. After that it then looks for the associated LOOKUPRoleID for a certain user. If the user doesn’t have a role assigned to it then it adds a new record to the database otherwise just update the table.

If you also noticed, I used a simple transaction within that method. This is because the table SYSUser, SYSUserProfile and SYSUserRole are pretty much related to each other and we need to make 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.

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

STEP 4: Modifying the UserManagePartial view

Now add the following HTML markup within "UserManagePartial.cshtml" view:

The initDialog variable initializes the jQueryUI dialog by customizing the dialog. We customized it by adding our own Save and Cancel button for us to write custom code implementation for each event. In the Save function we extracted each values from the edit form and pass 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 which 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 certain process if the request at the server 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 the 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: Modifying the ManageUserPartial Action method

If you remember, we added the new parameter "status" to the ManageUserPartial 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:

STEP 7: Displaying the Status result

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

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

STEP 8: Running the page

Here are the outputs below:

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. :)