Overview

In the ASP.Net MVC 5 project template there are various types of techniques by which we can perform the database operations like Create, Read, Update and Delete (CRUD) in the web application. We can use the Entity Framework approaches in the controller using an Entity Data Model and display it from the View. We can create the service for doing data operations and using a service reference we can call the operations using JavaScript like Angular, Knockout or jQuery in the web application.

This article shows how to create a web application using the ASP.NET Web API 2 project template and do some data operations like reading the data from the database and calling the Web API Controller method in the MVC Controller and call the adjacent view. I have created n layers of the application when creating this project. You will see multiple layers of the application in this project. I have applied the simple ADO.Net approach for doing the database operations.

Prerequisites

I am creating an article in which the web applications are created with the new Project Templates like ASP.Net Web API 2 and ASP.Net MVC 5 in the Visual Studio 2013, so there are the following prerequisites before getting started:

Getting Started

Let's begin with the following sections:

Creating Database

In this section we will create the database for the application. Begin with the following procedure.

Step 1

Create the database architecture with the following code:

  1. CREATE DATABASE [CollegeTracker]
  2. USE CollegeTracker
  3. CREATE TABLE [dbo].[CollegeDetails](
  4. [CollegeID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
  5. [CollegeName] [varchar](100) NULL,
  6. [CollegeAddress] [nvarchar](150) NULL,
  7. [CollegePhone] [bigint] NULL,
  8. [CollegeEmailID] [nvarchar](50) NULL,
  9. [ContactPerson] [varchar](50) NULL,
  10. [State] [varchar](100) NULL,
  11. [City] [varchar](100) NULL,
  12. )

Note: Insert some values into the table.

Step 2

Now, we'll create the Stored Procedure for reading the data with the following code:

  1. USE [CollegeTracker]
  2. Create Proc [dbo].[CT_CollegeDetails_Select]
  3. As
  4. Begin
  5. Select * From CollegeDetails
  6. End

Creating Project

In this section, we will create and add the application for doing the data operation and create the ASP.NET web application using the ASP.NET Web API 2 project template. We will create the separate project for the API and DAL to better understand the code.

At first we will create the main project to start the application. Let's follow the procedure given below.

Step 1

Open Visual Studio 2013 and click on "New Project".

Visual Studio 2013 Start Page

Step 2

Create the "ASP.Net Web Application" named "CollegeTracker" using the MVC Project Template.

Mvc Project Template

Visual Studio creates the web application with the MVC template.

Step 3

Create a new folder named "Web" in the Solution Explorer and move the MVC project into that folder.

Creating Model

At first we will create the Model for the application. A Model is the very essential part for the project. In the Model, we define the classes for the application. Use the procedure given below.

Step 1

Add a new folder named "Models" in the Solution Explorer.

Step 2

Add a new class library project named "CollegeTrackerModels" to the Models folder.

Creating Model

Note: Remove the automatically created class.

Step 3

Add a new class named "CollegeDetails" to the model project.

Step 4

Replace the code with the following code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. namespace CollegeTrackerModels
  5. {
  6. /// <summary>
  7. /// class for College Details
  8. /// </summary>
  9. public class CollegeDetails
  10. {
  11. #region Properties
  12. ///<summary>
  13. ///get and set the College ID
  14. ///</summary>
  15. public int CollegeID { get; set; }
  16. ///<summary>
  17. ///get and set the College Name
  18. ///</summary>
  19. [Display(Name = "College Name")]
  20. public string CollegeName { get; set; }
  21. ///<summary>
  22. ///get and set the College Address
  23. ///</summary>
  24. [Display(Name = "College Address")]
  25. public string CollegeAddress { get; set; }
  26. ///<summary>
  27. ///get and set the College Phone
  28. ///</summary>
  29. [Display(Name = "College Phone")]
  30. public Int64 CollegePhone { get; set; }
  31. ///<summary>
  32. ///get and set the College Email ID
  33. ///</summary>
  34. [Display(Name = "College EmailID")]
  35. public string CollegeEmailID { get; set; }
  36. ///<summary>
  37. ///get and set the Contact Person
  38. ///</summary>
  39. [Display(Name = "Contact Person")]
  40. public string ContactPerson { get; set; }
  41. ///<summary>
  42. ///get and set the State
  43. ///</summary>
  44. public string State { get; set; }
  45. ///<summary>
  46. ///get and set the City
  47. ///</summary>
  48. public string City { get; set; }
  49. #endregion
  50. }
  51. }

Creating Data Access Layer

Step 1

Create another folder named "Modules" by just right-clicking on the solution in the Solution Explorer and add a new Library Project to the Modules folder named "CollegeTrackerCore".

Creating Class Library

Note: Remove the automatically created class.

Step 2

Add two new folders named "BLL" and "DAL" to the project.

Step 3

Right-click on the DAL folder and add a new class named "CollegeDAL".

Creating DAL Class

Step 4

Replace the code with the following code in the CollegeDAL:

  1. using System;
  2. using System.Collections.Generic;
  3. using CollegeTrackerModels;
  4. using System.Configuration;
  5. using System.Data.SqlClient;
  6. using System.Data;
  7. namespace CollegeTrackerCore.DAL
  8. {
  9. public class CollegeDAL
  10. {
  11. #region Variables
  12. SqlConnection con;
  13. SqlCommand cmd;
  14. SqlDataAdapter adap;
  15. DataTable dt;
  16. DataSet ds;
  17. string connectionstring = ConfigurationManager.ConnectionStrings["CollegeTrackerConnectionString"].ConnectionString;
  18. #endregion
  19. #region Constructor
  20. public CollegeDAL()
  21. {
  22. con = new SqlConnection(this.connectionstring);
  23. }
  24. #endregion
  25. #region Public Method
  26. /// <summary>
  27. /// This method is used to get all College Details.
  28. /// </summary>
  29. /// <returns></returns>
  30. public List<CollegeDetails> GetAllCollegeDetails()
  31. {
  32. List<CollegeDetails> objCollegeDetails = new List<CollegeDetails>();
  33. using (cmd = new SqlCommand("CT_CollegeDetails_Select", con))
  34. {
  35. try
  36. {
  37. cmd.CommandType = CommandType.StoredProcedure;
  38. con.Open();
  39. adap = new SqlDataAdapter();
  40. adap.SelectCommand = cmd;
  41. dt = new DataTable();
  42. adap.Fill(dt);
  43. foreach (DataRow row in dt.Rows)
  44. {
  45. CollegeDetails col = new CollegeDetails();
  46. col.CollegeID = Convert.ToInt32(row["CollegeID"]);
  47. col.CollegeName = row["CollegeName"].ToString();
  48. col.CollegeAddress = row["CollegeAddress"].ToString();
  49. col.CollegePhone = Convert.ToInt64(row["CollegePhone"]);
  50. col.CollegeEmailID = row["CollegeEmailID"].ToString();
  51. col.ContactPerson = row["ContactPerson"].ToString();
  52. col.State = row["State"].ToString();
  53. col.City = row["City"].ToString();
  54. objCollegeDetails.Add(col);
  55. }
  56. }
  57. catch (Exception ex)
  58. {
  59. con.Close();
  60. }
  61. return objCollegeDetails;
  62. }
  63. }
  64. #endregion
  65. }
  66. }

Step 5

Now in the BLL folder add a new class named "CollegeBLCore".

Adding Class

Step 6

Replace the code with the following code:

  1. using CollegeTrackerCore.DAL;
  2. using CollegeTrackerModels;
  3. using System;
  4. using System.Collections.Generic;
  5. namespace CollegeTrackerCore.BLL
  6. {
  7. public abstract class CollegeBLCore
  8. {
  9. #region Public Method
  10. /// <summary>
  11. /// This method is used to get the College Details
  12. /// </summary>
  13. /// <returns></returns>
  14. protected List<CollegeDetails> GetAllCollegeDetails()
  15. {
  16. List<CollegeDetails> objCollegeDetails = null;
  17. try
  18. {
  19. objCollegeDetails = new CollegeDAL().GetAllCollegeDetails();
  20. }
  21. catch (Exception ex)
  22. {
  23. throw ex;
  24. }
  25. return objCollegeDetails;
  26. }
  27. #endregion
  28. }
  29. }

Creating API Project

In this project we'll create the API project for the application. We will define the controller in the Area in the application. Let's start with the following procedure.

Step 1

Create a new folder on the Solution Explorer named "API" and in it add a new project using the Web API Project Template named "CollegeTrackerAPI".

Creating API Project

Step 2

Add an Area by right-clicking on the API project and select Add -> Area.

Adding Area

Step 3

Remove all except the controller folder and add a new folder named "BLL".

Step 4

Add a new class in the BLL folder named "CollegeBL".

Adding Class in API

Step 5

Replace the code with the following code:

  1. using System.Collections.Generic;
  2. using CollegeTrackerCore.BLL;
  3. using CollegeTrackerModels;
  4. namespace CollegeTrackerAPI.Areas.BLL
  5. {
  6. internal sealed class CollegeBL : CollegeBLCore
  7. {
  8. /// <summary>
  9. /// This method is used to get the College Details
  10. /// </summary>
  11. /// <returns></returns>
  12. internal new List<CollegeDetails> GetAllCollegeDetails()
  13. {
  14. return base.GetAllCollegeDetails();
  15. }
  16. }
  17. }

Step 6

Right-click on the controller and go to Add -> Controller and select empty Web API 2 Controller as shown below:

Adding Web API 2 Empty Controller

Step 7

Enter the controller named "CollegeDetails".

Step 8

Replace the code with the following code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Http;
  5. using System.Web.Http;
  6. using CollegeTrackerModels;
  7. using CollegeTrackerAPI.Areas.BLL;
  8. namespace CollegeTrackerAPI.Areas.Controller
  9. {
  10. public class CollegeDetailsController : ApiController
  11. {
  12. #region Variable
  13. /// <summary>
  14. /// varibale for CollegeBL
  15. /// </summary>
  16. private CollegeBL objCollegeBL;
  17. /// <summary>
  18. /// variable for HttpResponseMessage
  19. /// </summary>
  20. HttpResponseMessage response;
  21. #endregion
  22. #region Response Method
  23. /// <summary>
  24. /// This method is used to fetch the College Details
  25. /// </summary>
  26. /// <returns></returns>
  27. [HttpGet, ActionName("GetAllCollegeDetails")]
  28. public HttpResponseMessage GetAllCollegeDetails()
  29. {
  30. objCollegeBL = new CollegeBL();
  31. HttpResponseMessage response;
  32. try
  33. {
  34. var detailsResponse = objCollegeBL.GetAllCollegeDetails();
  35. if (detailsResponse != null)
  36. response = Request.CreateResponse<List<CollegeDetails>>(HttpStatusCode.OK, detailsResponse);
  37. else
  38. response = new HttpResponseMessage(HttpStatusCode.NotFound);
  39. }
  40. catch (Exception ex)
  41. {
  42. response = Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
  43. }
  44. return response;
  45. }
  46. #endregion
  47. }
  48. }

Step 9

Open the Web.Config file and add the following code in the Connection String block:

  1. <add name="CollegeTrackerConnectionString" connectionString="Data Source=.; Initial Catalog=CollegeTracker; providerName="System.Data.SqlClient"/>

Creating User Interface Layer

We have almost created the application, now finally in this section we will create the User Interface and call the API Controller action method from the MVC Controller. To do this, follow the instruction below.

Step 1

Add a new controller by going to the Web Folder and in the CollegeTracker project go to the Controller folder and add a new controller as shown below:

Adding New Scaffolded Item

Step 2

Define the controller named "CollegeDetails" and add the following code to it:

  1. using CollegeTrackerModels;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Net.Http.Headers;
  5. using System.Threading.Tasks;
  6. using System.Web.Mvc;
  7. namespace CollegeTracker.Controllers
  8. {
  9. public class CollegeDetailsController : Controller
  10. {
  11. // GET: CollegeDetails
  12. public ActionResult Index()
  13. {
  14. return View();
  15. }
  16. [HttpGet, ActionName("getcollegelist")]
  17. public ActionResult GetCollegeList()
  18. {
  19. var list = new List<CollegeTrackerModels.CollegeDetails>();
  20. var httpClient = new HttpClient();
  21. httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  22. HttpResponseMessage response;
  23. response = httpClient.GetAsync("http://localhost:59866/api/" + "CollegeDetails/GetAllCollegeDetails/").Result;
  24. response.EnsureSuccessStatusCode();
  25. List<CollegeDetails> cd = response.Content.ReadAsAsync<List<CollegeDetails>>().Result;
  26. return View("~/Views/CollegeDetails/CollegeDetails.cshtml",cd );
  27. }
  28. }
  29. }

Step 3

Go to Views/CollegeDetails and add an empty view named "CollegeDetails" and replace the code with the following code:

  1. @model IEnumerable<CollegeTrackerModels.CollegeDetails>
  2. @{
  3. ViewBag.Title = "College Details";
  4. }
  5. <table class="table">
  6. <tr>
  7. <th>
  8. @Html.DisplayNameFor(model=> model.CollegeName)
  9. </th>
  10. <th>
  11. @Html.DisplayNameFor(model => model.CollegeAddress)
  12. </th>
  13. <th>
  14. @Html.DisplayNameFor(model => model.CollegePhone)
  15. </th>
  16. <th>
  17. @Html.DisplayNameFor(model => model.CollegeEmailID)
  18. </th>
  19. <th>
  20. @Html.DisplayNameFor(model => model.ContactPerson)
  21. </th>
  22. <th>
  23. @Html.DisplayNameFor(model => model.State)
  24. </th>
  25. <th>
  26. @Html.DisplayNameFor(model => model.City)
  27. </th>
  28. </tr>
  29. @foreach (var item in Model) {
  30. <tr>
  31. <td>
  32. @Html.DisplayFor(modelItem=>item.CollegeName)
  33. </td>
  34. <td>
  35. @Html.DisplayFor(modelItem=> item.CollegeAddress)
  36. </td>
  37. <td>
  38. @Html.DisplayFor(modelItem => item.CollegePhone)
  39. </td>
  40. <td>
  41. @Html.DisplayFor(modelItem => item.CollegeEmailID)
  42. </td>
  43. <td>
  44. @Html.DisplayFor(modelItem => item.ContactPerson)
  45. </td>
  46. <td>
  47. @Html.DisplayFor(modelItem => item.State)
  48. </td>
  49. <td>
  50. @Html.DisplayFor(modelItem => item.City)
  51. </td>
  52. <td>
  53. @Html.ActionLink("Edit", "Edit", new { id = item.CollegeID }) |
  54. @Html.ActionLink("Details", "Details", new { id = item.CollegeID }) |
  55. @Html.ActionLink("Delete", "Delete", new { id = item.CollegeID })
  56. </td>
  57. </tr>
  58. }
  59. </table>

Step 4

Go to the Views/Shared/_Layout.cshtml page and add an ActionLink with the following code:

  1. <li>@Html.ActionLink("College", "GetCollegeList", "CollegeDetails")</li>

Step 5

Go to the solution and right-click on it and select Set Startup Projects.

Set Startup Projects

Step 6

Since we have multiple projects we need to start the API Project and Web Project simultaneously. Select Start for both of the API and Web Projects.

Solution Property Pages

Step 7

Run the application and click on the College link.

Opening College View

Step 8

You can see the returned data from the API Controller.

College View

Summary

This article described how to call the Web API Controller method from the MVC Controller and view the returned data in the page. We will do the other operations in the next articles. Thanks for reading the article.