ASP.NET Web API with C# - Implementing GET method and accessing in C#,JQuery
Hello.. !!
We have seen how to create a ASP.NET Web API project and accessing it through localhost.
Now we will implement CRUD(Create, Read,Update, Delete) operations for the project we have seen earlier
Here is the project description
"Build a Web API project for a Super Market/ Mart where there is a huge DB warehouse of Products which are belongs to different categories and with prices. These products are associated with Sellers data. This DB warehouse also contains all Orders data associated with Customer details"
What we do in this article
We have implemented Web API methods and tested it only using XML string in browser
Let's use these methods by accessing it from C# code. We have a MVC web page which is rendering while running the solution in debug mode. So, we will add our testing methods in the same Controller and Views
function GetAllProducts(productID) {
var completeUrl = "https://localhost:44355/api/Product/GetAllProducts";
if (productID)
completeUrl = "https://localhost:44355/api/Product/GetProductDetail?productID=" + productID
$.ajax({
type: "get",
url: completeUrl,
dataType: "json",
contentType: "application/json;",
success: function (response) {
console.log(response);
}
});
}
Now, in Views/Shared/_Layout.cshtml
1. add <script src="~/Scripts/Products.js"></script> in head tag
2. Add two list items along with Home, API in <div class="navbar-collapse collapse">
<li><a href="#" onclick="GetAllProducts()">Get Products</a></li>
<li><a href="#" onclick="GetAllProducts(1)">Get First Product</a></li>
Run the application in debug mode and click F12 or Right click on browser -> inspect element
Now click Get Products on the screen and observe the below in console tab
Now click Get First Product on the screen and observe the below in console tab
After a long long scroll we've came to an end of this article. Hope you've got a clear picture of Web API method creation and accessing it from C# and JQuery. We can access API methods from any language/platform. This is the beauty of Web APIs.
Download Web API solution
Download Web API Sample Code Files
If you have any doubts, post them in the comment section below
Thanks..!!!!
The Midnight Coder
We have seen how to create a ASP.NET Web API project and accessing it through localhost.
Now we will implement CRUD(Create, Read,Update, Delete) operations for the project we have seen earlier
Here is the project description
"Build a Web API project for a Super Market/ Mart where there is a huge DB warehouse of Products which are belongs to different categories and with prices. These products are associated with Sellers data. This DB warehouse also contains all Orders data associated with Customer details"
What we do in this article
- Adding a Model
- Implement GET operation
- Access it from C# and Javascript
Download Web API solution
Download Web API Sample Code Files
First we need to create a Web API project. You can easily follow this link to know how to create it. After having all these set, we can move further
Download Web API Sample Code Files
First we need to create a Web API project. You can easily follow this link to know how to create it. After having all these set, we can move further
Adding a Model
Right Click on the Model folder -> Add -> New Item -> Class
Give it a name and click Add
New file which is having cs extension will be added with the given name. This is called Model in MVC Framework. This holds properties of the Entity we have defined
For example, Product is a class name. Product will have features/properties like
Name - string- Name of the product
Category - string - Category it belongs to. Health, Electronics etc
Price - decimal - MRP of the price
ProductID - int- Id which uniquely identifies that product
ProductCode- string - Which was given by the manufacturer or by the seller
I have added below 4 models to the project
public class Product
{
public string Name { get ; set ; }
public int ProductID { get; set; }
public string ProductCode { get; set; }
public int TotalQuantity { get; set; }
public int AvailableQuantity { get; set; }
public string ProductCategory{ get; set; }
public decimal Price { get; set; }
public int SellerID { get; set; }
}
Implement GET operation
Now let's add API Methods to get some data by adding a new API Controller
Right click Controllers -> Add -> Controller -> Web API 2 Controller
Give it a name(in my case ProductController), controller word in the name will be added automatically by framework. click add
Now, a controller class will be added in the folder, if we observe the class, it is implementing ApiController instead of Controller which means added is a Web API Controller
Add below in the ProductController
public static List<Product> products = new List<Product>();
public void SetProductDetails()
{
products.Add(new Product()
{
Name = "AXE Refresh Deo",
AvailableQuantity = 10,
Price = 190,
ProductCategory = "Deo&Perfumes",
ProductCode = "AXERDM12",
ProductID = 1,
SellerID = 1,
TotalQuantity = 15
});
products.Add(new Product()
{
Name = "Killer Jeans",
AvailableQuantity = 25,
Price = 3499,
ProductCategory = "MensWear",
ProductCode = "KillerXJ900",
ProductID = 2,
SellerID = 1,
TotalQuantity = 53
});
products.Add(new Product()
{
Name = "Rebook Shoes",
AvailableQuantity = 23,
Price = 3250,
ProductCategory = "Shoes",
ProductCode = "RBKM093",
ProductID = 3,
SellerID = 1,
TotalQuantity = 42
});
}
{
products.Add(new Product()
{
Name = "AXE Refresh Deo",
AvailableQuantity = 10,
Price = 190,
ProductCategory = "Deo&Perfumes",
ProductCode = "AXERDM12",
ProductID = 1,
SellerID = 1,
TotalQuantity = 15
});
products.Add(new Product()
{
Name = "Killer Jeans",
AvailableQuantity = 25,
Price = 3499,
ProductCategory = "MensWear",
ProductCode = "KillerXJ900",
ProductID = 2,
SellerID = 1,
TotalQuantity = 53
});
products.Add(new Product()
{
Name = "Rebook Shoes",
AvailableQuantity = 23,
Price = 3250,
ProductCategory = "Shoes",
ProductCode = "RBKM093",
ProductID = 3,
SellerID = 1,
TotalQuantity = 42
});
}
public IEnumerable<Product> GetAllProducts()
{
if (products.Count == 0)
SetProductDetails();
return products;
}
public Product GetProductDetail(int productID)
{
if (products.Count == 0)
SetProductDetails();
return products.Where(x => x.ProductID == productID).FirstOrDefault();
}
Note: Here we are preparing products list manually in SetProductDetails(). Generally these details will be pulled from database server
Build the solution and browse the Web API project it in debug mode
Note: Port number may be different in your case because it is dynamic
browse https://localhost:44355/api/Product/GetAllProducts or https://localhost:44355/api/Product/
will get below result
Above method is returning all the product details
Browse https://localhost:44355/api/Product/GetProductDetail?productID=1
Accessing API methods from C#
We have implemented Web API methods and tested it only using XML string in browser
Let's use these methods by accessing it from C# code. We have a MVC web page which is rendering while running the solution in debug mode. So, we will add our testing methods in the same Controller and Views
Add below method in HomeController.cs
public async Task<ActionResult> GetProductsFromAPI(int productID=0)
{
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44355/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
Product product = null;
List<Product> products = new List<Product>();
if (productID > 0)
{
HttpResponseMessage response = await client.GetAsync("api/Product/GetProductDetail?productID=1");
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
products.Add(product);
}
//return Json(product, JsonRequestBehavior
// .AllowGet);
}
else
{
HttpResponseMessage response = await client.GetAsync("api/Product/GetAllProducts");
if (response.IsSuccessStatusCode)
{
products = await response.Content.ReadAsAsync<List<Product>>();
}
//return Json(product, JsonRequestBehavior
// .AllowGet);
}
return View(products);
}
Add below code in GetProductsFromAPI.cshtml in Views/Home
You can simple Right click on the GetProductsFromAPI() method in HomeController and select Add View and replace below code over there
@model IEnumerable<isMART.API.Models.Product>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetProductsFromAPI</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table" cellpadding="10" cellspacing="10" border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.ProductCode)
</th>
<th>
@Html.DisplayNameFor(model => model.TotalQuantity)
</th>
<th>
@Html.DisplayNameFor(model => model.AvailableQuantity)
</th>
<th>
@Html.DisplayNameFor(model => model.ProductCategory)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.SellerID)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductCode)
</td>
<td>
@Html.DisplayFor(modelItem => item.TotalQuantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.AvailableQuantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductCategory)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.SellerID)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
@Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProductID })
</td>
</tr>
}
</table>
</body>
</html>
Now run the application in debug mode
Browse https://localhost:44355/home/GetProductsFromAPI
Browse https://localhost:44355/home/GetProductsFromAPI?productID=2
Accessing API methods from JQuery
We need to use JQuery and access Web API through AJAX call
Right click Scripts -> Add -> JavaScript File
Add below code in GetProductsFromAPI.cshtml in Views/Home
You can simple Right click on the GetProductsFromAPI() method in HomeController and select Add View and replace below code over there
@model IEnumerable<isMART.API.Models.Product>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetProductsFromAPI</title>
</head>
<body>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table" cellpadding="10" cellspacing="10" border="1">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.ProductCode)
</th>
<th>
@Html.DisplayNameFor(model => model.TotalQuantity)
</th>
<th>
@Html.DisplayNameFor(model => model.AvailableQuantity)
</th>
<th>
@Html.DisplayNameFor(model => model.ProductCategory)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.SellerID)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductCode)
</td>
<td>
@Html.DisplayFor(modelItem => item.TotalQuantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.AvailableQuantity)
</td>
<td>
@Html.DisplayFor(modelItem => item.ProductCategory)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.SellerID)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
@Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ProductID })
</td>
</tr>
}
</table>
</body>
</html>
Browse https://localhost:44355/home/GetProductsFromAPI
Browse https://localhost:44355/home/GetProductsFromAPI?productID=2
Accessing API methods from JQuery
We need to use JQuery and access Web API through AJAX call
Right click Scripts -> Add -> JavaScript File
Give it a name(Product) and add below function in the file
function GetAllProducts(productID) {
var completeUrl = "https://localhost:44355/api/Product/GetAllProducts";
if (productID)
completeUrl = "https://localhost:44355/api/Product/GetProductDetail?productID=" + productID
$.ajax({
type: "get",
url: completeUrl,
dataType: "json",
contentType: "application/json;",
success: function (response) {
console.log(response);
}
});
}
Now, in Views/Shared/_Layout.cshtml
1. add <script src="~/Scripts/Products.js"></script> in head tag
2. Add two list items along with Home, API in <div class="navbar-collapse collapse">
<li><a href="#" onclick="GetAllProducts()">Get Products</a></li>
<li><a href="#" onclick="GetAllProducts(1)">Get First Product</a></li>
Run the application in debug mode and click F12 or Right click on browser -> inspect element
Now click Get Products on the screen and observe the below in console tab
Now click Get First Product on the screen and observe the below in console tab
After a long long scroll we've came to an end of this article. Hope you've got a clear picture of Web API method creation and accessing it from C# and JQuery. We can access API methods from any language/platform. This is the beauty of Web APIs.
Download Web API solution
Download Web API Sample Code Files
If you have any doubts, post them in the comment section below
Thanks..!!!!
The Midnight Coder
Comments
Post a Comment