Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Model
The CustomerModel class consists of the following properties.
public class CustomerModel
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Controller
The Web API Controller
In order to add a Web API Controller, you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option and then give it a suitable name and click Add.
Namespaces
You will need to import the following namespaces in the Web API Controller.
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Http;
The Web API Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, the records are fetched from the Customers Table using SqlDataReader and then using WHILE Loop, the records are copied into the Generic List collection of CustomerModel class objects.
Note: This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpGet attribute which signifies that the method will accept HTTP GET requests.
Finally, the Generic List Collection of CustomerModel class objects are returned.
public class CustomerAPIController : ApiController
{
[HttpGet]
[Route("api/CustomerAPI/GetCustomers")]
public List<CustomerModel> GetCustomers()
{
List<CustomerModel> customers = new List<CustomerModel>();
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT CustomerId, Name, Country FROM Customers";
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new CustomerModel
{
CustomerId = int.Parse(sdr["CustomerId"].ToString()),
Name = sdr["Name"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
}
}
return customers;
}
}
The MVC Controller
Namespaces
You will need to import the following namespaces in the MVC Controller.
using System.Net.Http;
using System.Web.Script.Serialization;
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, the URL of the Web API along with its Controller method is passed to the GetAsync method of the HttpClient class.
The GetAsync method of the HttpClient class calls the Web API’s Controller method i.e. the GetCustomers method and returns the JSON string which is then de-serialized to Generic List of CustomerModel class objects and finally, returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<CustomerModel> customers = new List<CustomerModel>();
string apiUrl = "http://localhost:7115/api/CustomerAPI/GetCustomers";
HttpClient client = new HttpClient();
HttpResponseMessage response = client.GetAsync(apiUrl).Result;
if (response.IsSuccessStatusCode)
{
customers = (new JavaScriptSerializer()).Deserialize<List<CustomerModel>>(response.Content.ReadAsStringAsync().Result);
}
return View(customers);
}
}
View
Inside the View, in the very first line the CustomerModel class is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@using WebAPI_ADO_MVC.Models
@model IEnumerable<CustomerModel>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerId</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (CustomerModel customer in Model)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads