In this session, I will show you CRUD operations using ASP.NET Web API in MVC, AngularJS.
Before going through this session, visit my previous sessions,
Note
It supports Single Page Applications; that is, at first the entire page is loaded in the client by the initial request, after that, the subsequent action has to be updated by Ajax request and there is no need to reload the entire page. The SPA reduces the response time to user actions and the result is a more fluid experience. Then I will show you how to create SPA and CRUD by using ASP.NET Web API, AngularJS.
Steps to be followed.
Step 1
Create a table called 'Customer'.
Sql Syntax
- CREATE TABLE [dbo].[Customer1](
- [Id] [int] NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Address] [nvarchar](50) NULL,
- [City] [nvarchar](50) NULL,
- [Country] [nvarchar](50) NULL,
- [DateOfBirth] [datetime] NULL,
- [Age] [int] NULL,
- CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS =
- ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
Step 2
Create a MVC web application named CRUDWebAPI.
Step 3
Create Entity Frame Work Model Object named "CrystalGranite2016.edmx" by taking above mentioned table name.
Step 4
Then create a Web API 2 controller named "CustomerController.cs" .
Code Ref
In the above mentioned code, I have described code functionality with a green comment line.
-
- protected override void Dispose(bool disposing)
- {
- db.Dispose();
- base.Dispose(disposing);
- }
Step 5
Support Single page application interface.
Open the Package Manager Console from Tools > Library Package Manager. Type the following command to install the AngularJS.Core NuGet package.
- Install-Package AngularJS.Core
In my system, I have installed AngularJS.Core.1.6.8.
Step 6
In Solution Explorer, right-click the Scripts folder, select Add | New Folder. Name the folder app and press Enter. Right-click the app folder you just created and select Add | JavaScript File named "customerCtrl.js".
Code Ref
-
- (function () {
- 'use strict';
-
-
- var app = angular.module('app', []);
- app.controller('customerController', ['$scope', '$http', customerController]);
-
-
- function customerController($scope, $http) {
-
-
- $scope.loading = true;
- $scope.addMode = false;
-
-
- $http.get('/api/Customer/').success(function (data) {
- $scope.customers = data;
- $scope.loading = false;
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- $scope.loading = false;
- });
-
-
- $scope.toggleEdit = function () {
- this.customer.editMode = !this.customer.editMode;
- };
-
-
- $scope.toggleAdd = function () {
- $scope.addMode = !$scope.addMode;
- };
-
-
- $scope.add = function () {
- $scope.loading = true;
- $http.post('/api/Customer/', this.newcustomer).success(function (data) {
- alert("Added Successfully!!");
- $scope.addMode = false;
- $scope.customers.push(data);
- $scope.loading = false;
- }).error(function (data) {
- $scope.error = "An Error has occured while Adding Customer! " + data;
- $scope.loading = false;
- });
- };
-
-
- $scope.save = function () {
- alert("Edit");
- $scope.loading = true;
- var frien = this.customer;
- alert(frien);
- $http.put('/api/Customer/' + frien.Id, frien).success(function (data) {
- alert("Saved Successfully!!");
- frien.editMode = false;
- $scope.loading = false;
- }).error(function (data) {
- $scope.error = "An Error has occured while Saving customer! " + data;
- $scope.loading = false;
- });
- };
-
-
- $scope.deletecustomer = function () {
- $scope.loading = true;
- var Id = this.customer.Id;
- $http.delete('/api/Customer/' + Id).success(function (data) {
- alert("Deleted Successfully!!");
- $.each($scope.customers, function (i) {
- if ($scope.customers[i].Id === Id) {
- $scope.customers.splice(i, 1);
- return false;
- }
- });
- $scope.loading = false;
- }).error(function (data) {
- $scope.error = "An Error has occured while Saving Customer! " + data;
- $scope.loading = false;
- });
- };
- }
- })();
Code Description
In the above-mentioned code, I have described code functionality with a green comment line.
-
- $http.get('/api/Customer/').success(function (data) {
- $scope.customers = data;
- $scope.loading = false;
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- $scope.loading = false;
- });
Step 7
Modify _Layout.cshtml page as mentioned below.
Code Ref
- <!DOCTYPE html>
- <html data-ng-app="app">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - My ASP.NET Application</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
-
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- @Html.ActionLink("Application name", "Index", "Home", null, new { @class = "navbar-brand" })
- </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav">
- <li>@Html.ActionLink("Home", "Index", "Home")</li>
- <li>@Html.ActionLink("About", "About", "Home")</li>
- <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
- @Html.Partial("_LoginPartial")
- </ul>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- @*<p>© @DateTime.Now.Year - My ASP.NET Application</p>*@
- <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© @DateTime.Now.ToLocalTime()</p>
- </footer>
- </div>
-
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @Scripts.Render("~/bundles/angularjs")
- @Scripts.Render("~/bundles/appjs")
-
- @RenderSection("scripts", required: false)
- </body>
- </html>
Code Description
Here, I have mentioned the path of Javascript references.
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @Scripts.Render("~/bundles/angularjs")
- @Scripts.Render("~/bundles/appjs")
Step 8
Modify code In BundleConfig.cs file, path is App_Start> BundleConfig.cs as mentioned below.
Code Ref
- using System.Web;
- using System.Web.Optimization;
-
- namespace CRUDWebAPI
- {
- public class BundleConfig
- {
-
- public static void RegisterBundles(BundleCollection bundles)
- {
- bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
- "~/Scripts/jquery-{version}.js"));
-
- bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
- "~/Scripts/jquery.validate*"));
-
-
-
- bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
- "~/Scripts/modernizr-*"));
-
- bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
- "~/Scripts/bootstrap.js",
- "~/Scripts/respond.js"));
-
- bundles.Add(new StyleBundle("~/Content/css").Include(
- "~/Content/bootstrap.css",
- "~/Content/site.css"));
-
-
- bundles.Add(new ScriptBundle("~/bundles/angularjs").Include(
- "~/Scripts/angular.min.js"));
-
- bundles.Add(new ScriptBundle("~/bundles/appjs").Include(
- "~/Scripts/app/customerCtrl.js"));
- }
- }
- }
Code Description
Here, I loaded file configuration from path as reference mentioned in _Layout.cshtml file.
- bundles.Add(new ScriptBundle("~/bundles/angularjs").Include(
- "~/Scripts/angular.min.js"));
-
- bundles.Add(new ScriptBundle("~/bundles/appjs").Include(
- "~/Scripts/app/customerCtrl.js"));
Step 9
I have added a gif image loader during page processing called satyaloader.gif in Images Folder.
Step 10
Create index view for CRUD Operation User Interface called Index.cshtml.
Code Ref
I have set AngularJS file path that supports single page application interface mentioned in _Layout.cshtml.
For the above reason I can use AngularJS controller name to perform crud operation as mentioned below in Index.cshtml.
- <div data-ng-controller="customerController" class="container">
- <div class="row">
- <div class="col-md-12">
After saving, data will shown in the below mentioned table with Edit and Delete link and after clicking on it data will be visible in table data by which we can modify data.
- table class="table table-bordered table-hover" style="width:800px">
- <tr>
- <th style="background-color: Yellow;color: blue" >ID</th>
- <td style="background-color: Yellow;color: blue">FirstName</td>
- <th style="background-color: Yellow;color: blue">LastName</th>
- <th style="background-color: Yellow;color: blue">Address</th>
- <th style="background-color: Yellow;color: blue">City</th>
- <th style="background-color: Yellow;color: blue">Country</th>
- <th style="background-color: Yellow;color: blue"></th>
- </tr>
- <tr data-ng-repeat="customer in customers">
- <td><strong data-ng-hide="customer.editMode">{{ customer.Id }}</strong></td>
- <td>
- <p data-ng-hide="customer.editMode">{{ customer.Name }}</p>
- <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Name" />
- </td>
In td section of table two tags are used, one is for records details with edit and delete link and another is after clicking on edit linking the data can be editable in textbox by using AngularJS directives data-ng-hide and data-ng-show.
- <td>
- <p data-ng-hide="customer.editMode">{{ customer.Name }}</p>
- <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Name" />
- </td>
- <td>
- <p data-ng-hide="customer.editMode">{{ customer.Address }}</p>
- <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Address" />
- </td>
After clicking on Edit link the options will be shown as Save and Cancel option with data editable textboxes.
- <p data-ng-hide="customer.editMode"><a data-ng-click="toggleEdit(customer)" href="javascript:;">Edit</a> | <a data-ng-click="deletecustomer(customer)" href="javascript:;">Delete</a></p>
- <p data-ng-show="customer.editMode"><a data-ng-click="save(customer)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(customer)" href="javascript:;">Cancel</a></p>
I have used gif image page loader.
- <div id="mydiv" data-ng-show="loading">
- <img src="Images/satyaloader.gif" class="ajax-loader" />
- </div>
OUTPUT
The page loader will be shown while fetching records.
Then UI for inserting records.
After Inserting records the UI will be shown like this.
After the data is inserted successfully, the alert message will be shown.
To update records:
To delete records.
SUMMARY
- CRUD Operation Using Web API.
- AngularJS Single page application Interface Support.
- Page loader during page process.