Introduction
AngularJS is an MVC based framework. Google developed AngularJS. AngularJS is an open source project, which can be used freely, modified and shared by others.
Top features Of AngularJS
- Two Way Data-Binding
This means that any changes to the model updates the view and any changes to the view updates the model.
- Dependency Injection
AngularJS has a built-in Dependency Injection, which makes application easier to develop, maintain and debug in addition to the test.
- Testing
Angular will test any of its code through both unit testing and end-to-end testing.
- Model View Controller
Split your application into MVC components. Maintaining these components and connecting them together means setting up Angular.
To build AngularJS Applications, you should download the script file and it is angular.js. To get the script file, visit https://angularjs.org.
Angular MVC
In AngularJS, MVC is implemented in JavaScript and HTML. The view is defined in an HTML form, while the model and controller are implemented in JavaScript. There are several methods by which these components can be put together in AngularJS.
Views
View in an AngularJS application is created with an HTML. The body of HTML that makes up View will be stored in separate files.
Directives In AngularJS
AngularJS directives are used in HTML.
- ng-app − Starts an AngularJS Application.
- ng-init − Initializes the Application data.
- ng-model − Binds the values of AngularJS Application data to HTML input controls.
- ng-repeat − Repeats HTML elements for each item in a collection.
Controllers in an AngularJS
AngularJS application has controllers to control the flow of data in the application. A Controller is controlled, using ng-controller directive. A controller is a JavaScript object, which contains attributes, properties and functions. Each Controller accepts $scope as a parameter , which refers to the application module that the controller is to control.
Filters In AngularJS
Filters are used to modify the data and can be used in an expression or Directives using pipe character.
- uppercase converts text to upper case text.
- lowercase converts text to lower case text.
- currency formats text in a currency format.
- filter- It filters the array to a subset of it based on its provided criteria.
- order by- It orders the array based on its provided criteria.
Module In AngularJS
Modules are used to separate Services, Controllers, Application etc. We define modules in separate JS files. Two types of modules are give below.
- Application Module − It is used to initialize an application with controller(s).
- Controller Module − It is used to define Controller.
Scope In AngularJS
Scope is a JavaScript object, which plays the role of joining Controller with the Views. Scope contains the model data. In Controllers, model data is accessed via $scope object.
$scope is passed as a first argument to controller.$scope.message and $scope.type are the models, which are to be used in an HTML page. We have set the values to models, which will be reflected in the application module. We can define the functions as well in $scope.
Custom Directives in AngularJS
Custom Directives are used in AngularJS to enhance the functionality of HTML. Custom Directives are defined, using Directive function. AngularJS application during Bootstrap finds the matching elements and does a one time activity, using its compile() method of the custom Directive. It then processes the element, using link() method of the custom Directive, which is based on the scope of Directive.
Types of Custom Directives
Element Directives activate when a matching element is encountered. Attribute Directive activates when a matching attribute is encountered. CSS Directive activates when a matching CSS style is encountered. Comment Directive activates when a matching comment is encountered.
Internationalization In AngularJS
AngularJS supports an inbuilt internationalization for three types of filters: currency, date and numbers. We only need to use corresponding JS according to locale of the country. By default, it will take the locale of the Browser.
Includes in AngularJS
To achieve embedded HTML pages inside HTML page functionality, the following ways are used − using AJAX. Make a Server call to get the corresponding HTML page and set it in an inner HTML of HTML control. Using Server side Includes JSP, PHP and other Web site Server technologies can include HTML pages. Using AngularJS, we can embed HTML pages within a HTML page, using ng-include Directive.
AJAX In AngularJS
AngularJS provides $https: control, which works as a Service to retrieve the data from the Server. The Server makes a database call to get the required records. AngularJS needs data in JSON format. Once the data is ready, $https can be used to get the data from the Server.
Steps to build AngularJs Mvc app to perform Crud functionality.
Step 1
First create an ASP.NET MVC 4 Application named “SatyaAngularjsWebApi”.
Step 2
Now, create a MDF file named “Database1.mdf” inside App_Data folder.
Step 3
Now, create one table and single stored procedure to perform Crud functionality .
Table Script
- CREATE TABLE[dbo].[Employee](
- [Id] INT IDENTITY(1, 1) NOT NULL, [Name] NVARCHAR(50) NOT NULL, [Address] NVARCHAR(50) NOT NULL, [Country] NVARCHAR(50) NOT NULL, [City] NVARCHAR(50) NOT NULL, [Mobile] NVARCHAR(10) NOT NULL, PRIMARY KEY CLUSTERED([Id] ASC));
Stored Procedure Script
- CREATE PROCEDURE sp_InsUpdDelEmployee
- @id int,
- @name nvarchar(50),
- @address nvarchar(50),
- @country nvarchar(50),
- @city nvarchar(50),
- @mobile nvarchar(50),
- @type varchar(10)
- AS
- Begin
- if (@type = 'Ins') Begin
- insert into Employee
- values(@name, @address, @country, @city, @mobile)
- End
- if (@type = 'Upd') Begin
- update Employee
- set Name = @name, [Address] = @address,
- Country = @country,
- City = @city,
- Mobile = @mobile
- where Id = @id
- End
- if (@type = 'Del') Begin
- delete from Employee
- where Id = @id
- End
- if (@type = 'GetById') Begin
- select * from Employee
- where Id = @id
- End
- select * from Employee
- End
Stored Procedure Script description
I have added 4 different types, using @type parameter to perform CRUD operation.
For Insert
- if (@type = 'Ins') Begin
- insert into Employee
- values(@name, @address, @country, @city, @mobile)
- End
For Update
- if (@type = 'Upd') Begin
- update Employee
- set Name = @name, [Address] = @address,
- Country = @country,
- City = @city,
- Mobile = @mobile
- where Id = @id
- End
For Delete
- if (@type = 'Del') Begin
- delete from Employee
- where Id = @id
- End
For Get By Id
- if (@type = 'GetById') Begin
- select * from Employee
- where Id = @id
- End
- select * from Employee
- End
There is no need to create connection string in web.config file. It can be run anywhere any time.
All systems generate the connection string in Web.Config file.
Code Ref
- <connectionStrings>
- <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-SatyaAngularjsWebApi-20170324113216;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-SatyaAngularjsWebApi-20170324113216.mdf" providerName="System.Data.SqlClient" />
- <add name="Database1Entities" connectionString="metadata=res://*/Models.Model.csdl|res://*/Models.Model.ssdl|res://*/Models.Model.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
- </connectionStrings>
Step 4
Create a Controller class file named “EmployeeAPIController.cs”.
Code Ref
- using SatyaAngularjsWebApi.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Data;
- using System.Data.Entity.Infrastructure;
- namespace SatyaAngularjsWebApi {
- public class EmployeeAPIController: ApiController {
-
- [HttpGet]
- public List < Employee > Get() {
- List < Employee > emplist = new List < Employee > ();
- using(Database1Entities db = new Database1Entities()) {
- var results = db.sp_InsUpdDelEmployee(0, "", "", "", "", "", "Get").ToList();
- foreach(var result in results) {
- var employee = new Employee() {
- Id = result.Id,
- Name = result.Name,
- Address = result.Address,
- Country = result.Country,
- City = result.City,
- Mobile = result.Mobile
- };
- emplist.Add(employee);
- }
- return emplist;
- }
- }
-
- public Employee Get(int id) {
- using(Database1Entities db = new Database1Entities()) {
- Employee employee = db.Employees.Find(id);
- if (employee == null) {
- throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
- }
- return employee;
- }
- }
-
- public HttpResponseMessage Post(Employee employee) {
- if (ModelState.IsValid) {
- using(Database1Entities db = new Database1Entities()) {
- var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList();
- HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, emplist);
- return response;
- }
- } else {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- }
-
- public HttpResponseMessage Put(Employee employee) {
- List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();
- if (!ModelState.IsValid) {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- using(Database1Entities db = new Database1Entities()) {
- try {
- emplist = db.sp_InsUpdDelEmployee(employee.Id, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Upd").ToList();
- } catch (DbUpdateConcurrencyException ex) {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
- }
- }
- return Request.CreateResponse(HttpStatusCode.OK, emplist);
- }
-
- public HttpResponseMessage Delete(int id) {
- using(Database1Entities db = new Database1Entities()) {
- List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();
- var results = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "GetById").ToList();
- if (results.Count == 0) {
- return Request.CreateResponse(HttpStatusCode.NotFound);
- }
- try {
- emplist = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "Del").ToList();
- } catch (DbUpdateConcurrencyException ex) {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
- }
- return Request.CreateResponse(HttpStatusCode.OK, emplist);
- }
- }
-
- protected override void Dispose(bool disposing) {
- using(Database1Entities db = new Database1Entities())
- db.Dispose();
- base.Dispose(disposing);
- }
- }
- }
Code description
We have to add the following namespaces to create the functionality in MVC, using AngularJS and WebAPI.
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using System.Data;
- using System.Data.Entity.Infrastructure;
To get all the employees, write the code, as shown below.
- [HttpGet]
- public List < Employee > Get() {
- List < Employee > emplist = new List < Employee > ();
- using(Database1Entities db = new Database1Entities()) {
- var results = db.sp_InsUpdDelEmployee(0, "", "", "", "", "", "Get").ToList();
- foreach(var result in results) {
- var employee = new Employee() {
- Id = result.Id,
- Name = result.Name,
- Address = result.Address,
- Country = result.Country,
- City = result.City,
- Mobile = result.Mobile
- };
- emplist.Add(employee);
- }
- return emplist;
- }
- }
Here, Database1Entities is a Auto generate model class file, which is related with Database1.mdf file.
This class helps us to connect to the Data Source and perform Insert, Update, Delete, Retrieve operation.
- List<Employee> emplist = new List<Employee>();
Here, Employee name of the table acts as a list generic class.
- var results = db.sp_InsUpdDelEmployee(0, "", "", "", "", "", "Get").ToList();
Here, “sp_InsUpdDelEmployee” is the name of the procedure.
To get employee by Id, follow the code given below.
- public Employee Get(int id) {
- using(Database1Entities db = new Database1Entities()) {
- Employee employee = db.Employees.Find(id);
- if (employee == null) {
- throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
- }
- return employee;
- }
- }
Here, an id is the name of the column.
To insert New Employee details, follow the code given below.
- public HttpResponseMessage Post(Employee employee) {
- if (ModelState.IsValid) {
- using(Database1Entities db = new Database1Entities()) {
- var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList();
- HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, emplist);
- return response;
- }
- } else {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- }
Here, “Ins” type, mention using stored procedure.
var emplist = db.sp_InsUpdDelEmployee(0, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Ins").ToList();
To update the existing employee, follow the code given below.
- public HttpResponseMessage Put(Employee employee) {
- List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();
- if (!ModelState.IsValid) {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- using(Database1Entities db = new Database1Entities()) {
- try {
- emplist = db.sp_InsUpdDelEmployee(employee.Id, employee.Name, employee.Address, employee.Country, employee.City, employee.Mobile, "Upd").ToList();
- } catch (DbUpdateConcurrencyException ex) {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
- }
- }
- return Request.CreateResponse(HttpStatusCode.OK, emplist);
- }
Here “Upd” type is mentioned, using stored procedure.
To delete an employee by Id, proceed as shown below.
- public HttpResponseMessage Delete(int id) {
- using(Database1Entities db = new Database1Entities()) {
- List < sp_InsUpdDelEmployee_Result > emplist = new List < sp_InsUpdDelEmployee_Result > ();
- var results = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "GetById").ToList();
- if (results.Count == 0) {
- return Request.CreateResponse(HttpStatusCode.NotFound);
- }
- try {
- emplist = db.sp_InsUpdDelEmployee(id, "", "", "", "", "", "Del").ToList();
- } catch (DbUpdateConcurrencyException ex) {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
- }
- return Request.CreateResponse(HttpStatusCode.OK, emplist);
- }
- }
Here, “GetById” type is mentioned to take the particular employee data. Here, “Del” type is mentioned, using stored procedure.
To prevent Memory Leak here, use Dispose method.
- protected override void Dispose(bool disposing) {
- using(Database1Entities db = new Database1Entities())
- db.Dispose();
- base.Dispose(disposing);
- }
Step 5
Here, I will check the Model created create “Database1.mdf” file, using ADO.NET Entity Data Model.
You can check here the Auto Generate class or the database entity generated here. The Database1Entities with the table and stored procedure are given below.
Also, you can get Employee.Cs file inside Model class folder.
The name of ADO.NET Entity Data Model file is Model.edmx.
Step 6
Create another controller class file named TestController.cs to create one View.
Code Ref
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace SatyaAngularjsWebApi {
- public class TestController: Controller {
- public ActionResult Index() {
- return View();
- }
- }
- }
Code decription
Here, Index Controller action method is used to create one cshtml file i.e. action result returns type.
Step 7
Add a “bootstrap.css” reference file inside CSS folder to operate layout and design in AngularJS. It can be used as reference class in view cshtml file.
Step 8
Here, I have added one angular.js reference file inside JS folder. Here, all AngularJS related Directives, scope, functionalities and filters are mentioned here. Hence, all built in functionality of AngularJS will be handled by this JS file.
Step 9
Here, I have created one JS file for joining controller with the views, using $scope object.
Code Ref
- var app = angular.module('myApp', []);
- app.controller('employeeController', ['$scope', '$http', employeeController]);
-
- function employeeController($scope, $http) {
- $scope.loading = true;
- $scope.updateShow = false;
- $scope.addShow = true;
- $http.get('/api/EmployeeAPI/').success(function(data) {
- $scope.employees = data;
- }).error(function() {
- $scope.error = "An Error has occured while loading posts!";
- });
- $scope.add = function() {
- $scope.loading = true;
- $http.post('/api/EmployeeAPI/', this.newemployee).success(function(data) {
- $scope.employees = data;
- $scope.updateShow = false;
- $scope.addShow = true;
- $scope.newemployee = '';
- }).error(function(data) {
- $scope.error = "An Error has occured while Saving employee! " + data;
- });
- }
- $scope.edit = function() {
- var Id = this.employee.Id;
- $http.get('/api/EmployeeAPI/' + Id).success(function(data) {
- $scope.newemployee = data;
- $scope.updateShow = true;
- $scope.addShow = false;
- }).error(function() {
- $scope.error = "An Error has occured while loading posts!";
- });
- }
- $scope.update = function() {
- $scope.loading = true;
- console.log(this.newemployee);
- $http.put('/api/EmployeeAPI/', this.newemployee).success(function(data) {
- $scope.employees = data;
- $scope.updateShow = false;
- $scope.addShow = true;
- $scope.newemployee = '';
- }).error(function(data) {
- $scope.error = "An Error has occured while Updating employee! " + data;
- });
- }
- $scope.delete = function() {
- var Id = this.employee.Id;
- $scope.loading = true;
- $http.delete('/api/EmployeeAPI/' + Id).success(function(data) {
- $scope.employees = data;
- }).error(function(data) {
- $scope.error = "An Error has occured while Delete employee! " + data;
- });
- }
- $scope.cancel = function() {
- $scope.updateShow = false;
- $scope.addShow = true;
- $scope.newemployee = '';
- }
- }
Code decription
- var app = angular.module('myApp', []);
- app.controller('employeeController', ['$scope', '$http', employeeController]);
Here, I have added one controller name in Angular JS file named employeeController.
- function employeeController($scope, $http) {
- $scope.loading = true;
- $scope.updateShow = false;
- $scope.addShow = true;
Here, I added Angularjs Controller
- function employeeController($scope, $http)
Now, declare the variables.
- $scope.loading = true;
- $scope.updateShow = false;
- $scope.addShow = true;
To get all employee through API controller, write the code shown below.
- $http.get('/api/EmployeeAPI/').success(function(data) {
- $scope.employees = data;
- }).error(function() {
- $scope.error = "An Error has occured while loading posts!";
- });
The default route template mentioned is WebApiConfig.cs file.
- $http.get('/api/EmployeeAPI/')
To Insert an employee through API controller, write the code, as shown below.
- $scope.add = function() {
- $scope.loading = true;
- $http.post('/api/EmployeeAPI/', this.newemployee).success(function(data) {
- $scope.employees = data;
- $scope.updateShow = false;
- $scope.addShow = true;
- $scope.newemployee = '';
- }).error(function(data) {
- $scope.error = "An Error has occured while Saving employee! " + data;
- });
- }
To update an employee through API Controller. Write the code, as shown below.
- $scope.edit = function () {
-
- var Id = this.employee.Id;
-
- $http.get('/api/EmployeeAPI/' + Id).success(function (data) {
-
- $scope.newemployee = data;
-
- $scope.updateShow = true;
-
- $scope.addShow = false;
-
- }).error(function () {
-
- $scope.error = "An Error has occured while loading posts!";
-
- });
-
- }
-
-
-
- $scope.update = function () {
-
- $scope.loading = true;
-
- console.log(this.newemployee);
-
- $http.put('/api/EmployeeAPI/', this.newemployee).success(function (data) {
-
- $scope.employees = data;
-
- $scope.updateShow = false;
-
- $scope.addShow = true;
-
- $scope.newemployee = '';
-
- }).error(function (data) {
-
- $scope.error = "An Error has occured while Updating employee! " + data;
-
- });
-
- }
To delete an employee through API Controller, write the code, as shown below.
- $scope.delete = function() {
- var Id = this.employee.Id;
- $scope.loading = true;
- $http.delete('/api/EmployeeAPI/' + Id).success(function(data) {
- $scope.employees = data;
- }).error(function(data) {
- $scope.error = "An Error has occured while Delete employee! " + data;
- });
- }
To cancel an employee, write the code, as shown below.
- $scope.cancel = function () {
- $scope.updateShow = false;
- $scope.addShow = true;
- $scope.newemployee = '';
- }
Step 10
Check For “WebApiConfig.cs” for API Controller and “RouteConfig.cs” for normal Controller class file .
Code Ref. of WebApiConfig.cs
- public static void Register(HttpConfiguration config)
- {
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
This class file will configure “EmployeeAPIController.cs” API Controller class file.
Code Ref. of RouteConfig.cs
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
-
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Test", action = "Index", id = UrlParameter.Optional }
- );
- }
This class file will configure TestController.cs normal controller class file.
Step 11
Create a View named Index.cshtml.
Code Ref
- @Scripts.Render("~/js")
- @Styles.Render("~/css")
-
- <html ng-app="myApp">
- <head><title>Satyaprakash - MVC AngularJs With WebApi</title></head>
- <body>
- <div ng-controller="employeeController" class="container">
- <div class="row">
- <div class="col-md-12">
- <h3 class="header">EMPLOYEE CRUD USING ANGULARJS AND WEBAPI</h3>
- </div>
- </div>
- <div class="row">
- <div class="col-md-12">
- <strong class="error">{{error}}</strong>
- <form name="addemployee" style="width: 600px; margin: 0px auto;">
- <div class="form-group">
- <label for="cname" class="col-sm-2 control-label">Name:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="cname" placeholder="please enter your name" ng-model="newemployee.Name" required />
- </div>
- </div>
- <div class="form-group">
- <label for="address" class="col-sm-2 control-label">Address:</label>
- <div class="col-sm-10 space">
- <textarea class="form-control" id="address" placeholder="please enter your address" ng-model="newemployee.Address" required></textarea>
- </div>
- </div>
- <div class="form-group">
- <label for="country" class="col-sm-2 control-label">Domicile:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="country" placeholder="please enter your native" ng-model="newemployee.Country" required />
- </div>
- </div>
- <div class="form-group">
- <label for="city" class="col-sm-2 control-label">Town:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="city" placeholder="please enter your town" ng-model="newemployee.City" required />
- </div>
- </div>
- <div class="form-group">
- <label for="mobile" class="col-sm-2 control-label">Contact:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="mobile" placeholder="please enter your Contact no." ng-model="newemployee.Mobile" required />
- </div>
- </div>
- <br />
- <div class="form-group space">
- <div class="col-sm-offset-2 col-sm-10">
- <input type="submit" value="Insert" ng-click="add()" ng-show="addShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />
- <input type="submit" value="Update" ng-click="update()" ng-show="updateShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />
- <input type="button" value="Reset" ng-click="cancel()" class="btn btn-primary" />
- </div>
- </div>
- <br />
- </form>
- </div>
- </div>
- <div class="row">
- <div class="col-md-12">
- <div class="table-responsive">
- <table class="table table-bordered table-hover" style="width: 800px; margin-left: 170px;">
- <tr>
- <th>Name</th>
- <th>Address</th>
- <th>Domicile</th>
- <th>Town</th>
- <th>Contact</th>
- <th>Actions</th>
- </tr>
- <tr ng-repeat="employee in employees">
- <td>
- <p>{{ employee.Name }}</p>
- </td>
- <td>
- <p>{{ employee.Address }}</p>
- </td>
- <td>
- <p>{{ employee.Country }}</p>
- </td>
- <td>
- <p>{{ employee.City }}</p>
- </td>
- <td>
- <p>{{ employee.Mobile }}</p>
- </td>
- <td>
- <p><a ng-click="edit()" href="javascript:void(0);">Edit</a> | <a ng-click="delete()" href="javascript:void(0);">Delete</a></p>
- </td>
- </tr>
- </table>
- </div>
- </div>
- </div>
- </div>
- <footer>
- <p style="background-color: Yellow;text-align:center ; color:blue"> @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@
- </footer>
- </body>
- </html>
Code description
Here, I have added two reference files of CSS and JS file inside CSS and JS folder.
- @Scripts.Render("~/js")
- @Styles.Render("~/css")
To access the functionalities of “App.js” file, add one Directive with the file name.
To access the functionalities of “App.js” controller file, add one Directive with the file name.
- <div ng-controller="employeeController" class="container">
Here, I added some bootstral.css class file.
- <div class="row">
- <div class="col-md-12">
- <h3 class="header">EMPLOYEE CRUD USING ANGULARJS AND WEBAPI</h3>
- </div>
- </div>
Inside a form, I added some controls like textboxes and buttons with some properties.
- <form name="addemployee" style="width: 600px; margin: 0px auto;">
- <div class="form-group">
- <label for="cname" class="col-sm-2 control-label">Name:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="cname" placeholder="please enter your name" ng-model="newemployee.Name" required />
- </div>
- </div>
- <div class="form-group">
- <label for="address" class="col-sm-2 control-label">Address:</label>
- <div class="col-sm-10 space">
- <textarea class="form-control" id="address" placeholder="please enter your address" ng-model="newemployee.Address" required></textarea>
- </div>
- </div>
- <div class="form-group">
- <label for="country" class="col-sm-2 control-label">Domicile:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="country" placeholder="please enter your native" ng-model="newemployee.Country" required />
- </div>
- </div>
- <div class="form-group">
- <label for="city" class="col-sm-2 control-label">Town:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="city" placeholder="please enter your town" ng-model="newemployee.City" required />
- </div>
- </div>
- <div class="form-group">
- <label for="mobile" class="col-sm-2 control-label">Contact:</label>
- <div class="col-sm-10 space">
- <input type="text" class="form-control" id="mobile" placeholder="please enter your Contact no." ng-model="newemployee.Mobile" required />
- </div>
- </div>
- <br />
- <div class="form-group space">
- <div class="col-sm-offset-2 col-sm-10">
- <input type="submit" value="Insert" ng-click="add()" ng-show="addShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />
- <input type="submit" value="Update" ng-click="update()" ng-show="updateShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />
- <input type="button" value="Reset" ng-click="cancel()" class="btn btn-primary" />
- </div>
- </div>
- <br />
- </form>
Here, I added one error functionality, which is defined in “App.js” file, if during data load time.
- <strong class="error">{{error}}</strong>
Here, I added 3 button controls with very nice app.js and bootstrap.css properties.
- <input type="submit" value="Insert" ng-click="add()" ng-show="addShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />
- <input type="submit" value="Update" ng-click="update()" ng-show="updateShow" ng-disabled="!addemployee.$valid" class="btn btn-primary" />
- <input type="button" value="Reset" ng-click="cancel()" class="btn btn-primary" />
Here, “ng-click” attributes are mentioned to access create, update, delete, cancel/reset functionalities from “App.Js” file.
Here, “ng-show” , “ng-disabled” attributes are mentioned, which are based on the valid data which needs to be checked, if these are in the input controls or not.
Here, class “btn btn-primary” bootstrap class is used for design layout in button controls.
The button control will be changed, which is based on new data entry and updates an existing employee's details.
- <div class="row">
- <div class="col-md-12">
- <div class="table-responsive">
- <table class="table table-bordered table-hover" style="width: 800px; margin-left: 170px;">
- <tr>
- <th>Name</th>
- <th>Address</th>
- <th>Domicile</th>
- <th>Town</th>
- <th>Contact</th>
- <th>Actions</th>
- </tr>
- <tr ng-repeat="employee in employees">
- <td>
- <p>{{ employee.Name }}</p>
- </td>
- <td>
- <p>{{ employee.Address }}</p>
- </td>
- <td>
- <p>{{ employee.Country }}</p>
- </td>
- <td>
- <p>{{ employee.City }}</p>
- </td>
- <td>
- <p>{{ employee.Mobile }}</p>
- </td>
- <td>
- <p><a ng-click="edit()" href="javascript:void(0);">Edit</a> | <a ng-click="delete()" href="javascript:void(0);">Delete</a></p>
- </td>
- </tr>
- </table>
- </div>
- </div>
- </div>
- </div>
Here, I have added table style, using bootsrap.css file.
- <div class="table-responsive">
- <table class="table table-bordered table-hover" style="width: 800px; margin-left: 170px;">
Here, I added one table with all the column values as well as with edit and delete link functionalities.
- <tr>
- <th>Name</th>
- <th>Address</th>
- <th>Domicile</th>
- <th>Town</th>
- <th>Contact</th>
- <th>Actions</th>
- </tr>
- <tr ng-repeat="employee in employees">
- <td>
- <p>{{ employee.Name }}</p>
- </td>
- <td>
- <p>{{ employee.Address }}</p>
- </td>
- <td>
- <p>{{ employee.Country }}</p>
- </td>
- <td>
- <p>{{ employee.City }}</p>
- </td>
- <td>
- <p>{{ employee.Mobile }}</p>
- </td>
- <td>
The model class file with the entities are given below in Model.edmx.
- <td>
- <p>{{ employee.Name }}</p>
- </td>
- <td>
- <p>{{ employee.Address }}</p>
- </td>
- <td>
- <p>{{ employee.Country }}</p>
- </td>
- <td>
- <p>{{ employee.City }}</p>
- </td>
- <td>
- <p>{{ employee.Mobile }}</p>
- </td>
- The link button associate with “app.js” edit and delete functionalities using “ng-click” directives.
- <td>
- <p><a ng-click="edit()" href="javascript:void(0);">Edit</a> | <a ng-click="delete()" href="javascript:void(0);">Delete</a></p>
- </td>
Here, I have added footer section to show current date and time.
- <footer>
- <p style="background-color: Yellow;text-align:center ; color:blue"> @DateTime.Now.ToLocalTime()</p> @*Add Date Time*@
- </footer>
Step 12
Here, I have added some CSS and JS file reference in “BundleConfig.cs” file.
Code Ref
- public static void RegisterBundles(BundleCollection bundles)
- {
- bundles.Add(new ScriptBundle("~/js").Include(
- "~/js/angular.js",
- "~/js/app.js"));
-
- bundles.Add(new StyleBundle("~/css").Include(
- "~/css/bootstrap.css"));
- }
Application OutPut
The URL of this AngularJS and WebAPI MVC Application is given below.
http://localhost:52159/Test/index
Here, test is the Controller name and Index is the controller action method name.
Here, I will insert one record, as shown below in the table.
When I click the edit link, the button changed to Update and I changed Bangalore to Bangalore1.
Also, the data is updated from Bangalore to Bangalore1.
No entry is there in the respective text boxes. Thus, Insert button Is disabled.
After I put data in all textboxes the Insert Button Is Enabled.
After clicking, Reset button needs to be used. All the entries in textboxes are removed and again Insert button is disabled.
When we click delete link button, the data is deleted and table now has empty records.
The footer part of this page now shows date, time and some copyright information to make it look professional.
Summary
- What is AngularJS?
- Create WebAPI Controller and normal Controller.
- AngularJs and WebAPI relation in an App.js file.
- Bootstrap and AngularJS references used in View Cshtml file.