Getting Started CRUD Operation with AngularJS in MVC
Introduction
Before start writing this article, first think in my mind is that it should be easy to understand and easy to implement so now start writing my first article.
AngularJS is a Superheroic JavaScript MVW Framework/Binding Framework that is used for making rich, extensible web applications. It is used in Single Page Application (SPA) projects . It extends HTML DOM with additional attributes and makes it more responsive to user actions. The AngularJS is open source JavaScript framework.
AngularJS has two version
- 1x like 1.6,1.5, 1.4 version
- 2.0 version is latest version of AngularJS.
Note:- "In the Simple words, AngularJS helps to us bind HTML element to JavaScript objects."
Data Binding
AngularJS has two-way Data-binding. Data-binding is an automatic process of updating the view whenever the model changes, as well as updating the model whenever the view changes.
Figure 1: AngularJS Binding
Controller
AngularJS is defined controller using ng-controller directive. AngularJS will create a new instance object internally and binding it.Controller is attached to the DOM via the ng-controller directive.Scope is a special JavaScript object which plays the role of joining controller with the views. $scope refers to application which is to use the controller object.
Services
Services are JavaScript functions and are responsible to do a specific tasks only.
https://docs.angularjs.org/guide/services
AngularJS services are:
- Lazily instantiated – AngularJS only instantiates a service when an application component depends on it.
- Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.
$scope is angular services for angular scope management. $scope is define has parameter. Angular will automatic coming and inject $scope and give us this term is call Dependency injection(DI). AngularJS provides many inbuilt services for example, $https:, $route, $window, $location etc. Each service is responsible for a specific task for example, $https: is used to make Ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.
Note:- "Dependency injection(DI)" whenever a framework come and inject the objects rather than we created. It automatically creates objects based on requests, and injects them when required".
Start with code
We create a sample web application in C# along with AngularJS, using Visual Studio 2017. This application has the following features.
- Binding the data and shown in table list.
- Create, Edit and update user.
- Create a controller, services and modules.
First of all, we create a new web application in VS2017
We install AngularJS using nuGet package, as shown in following figure 2.
We Create UserViewModel class in c#
namespace CURD.Models
{
public class UserViewModel
{
public int? Id { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string CreatedDate { get; set; }
}
}
We Create Module.js file
var userApp = angular.module("userApp", []);
We Create UserServices.js file
userApp.service("userService", function ($http) {
var $this = this;
$this.AddEdit = function (user) {
var request = $http({
method: 'POST',
url: Domain + 'AddEditUser',
data: JSON.stringify(user),
dataType: "json"
});
return request;
}
$this.Delete = function (id) {
var request = $http({
method: 'POST',
url: Domain + 'DeleteUser',
data: "{ id:" + id + " }",
dataType: "json"
});
return request;
}
$this.GetAll = function () {
var request = $http({
method: 'GET',
url: Domain + 'GetAllUsers',
});
return request;
}
$this.GetUser = function (id) {
var request = $http({
method: 'GET',
url: Domain + 'GetUser/' + id,
});
return request;
}
});
Create UserController.js file
userApp.controller("userController", function ($scope, userService) {
GetUsers();
$scope.SaveUser = function () {
var UserModel = {
Id: $scope.id,
Email: $scope.email,
FirstName: $scope.firstName,
LastName: $scope.lastName,
Phone: $scope.phone
};
if (!CheckIsValid()) {
alert('Please fill the detail!');
return false;
}
var requestResponse = userService.AddEdit(UserModel);
Message(requestResponse);
};
$scope.editUser = function (id) {
var getData = userService.GetUser(id);
getData.then(function (user) {
var userData = user.data;
$scope.id = userData.Id;
$scope.email = userData.Email;
$scope.phone = userData.Phone;
},
function () {
alert('Error in getting records');
});
}
$scope.DeleteUser = function (id) {
var requestResponse = userService.Delete(id);
Message(requestResponse);
};
function GetUsers() {
var requestResponse = userService.GetAll();
requestResponse.then(function (response) {
$scope.employees = response.data;
}, function () {
})
};
function Message(requestResponse) {
requestResponse.then(function successCallback(response) {
GetUsers();
$('#addEditUser').modal('hide');
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function CheckIsValid() {
var isValid = true;
if ($('#email').val() === '' || $('#phone').val() === '' || $('#email').val() === '' || $('#phone').val() === '') {
isValid = false;
}
return isValid;
}
});
Now we will create a controller for the UI that handles all requests for the user add/edit/delete and shows the user list and also a view HTML template The following is the code snippet for UserController and views
using CURD.Code;
using CURD.Models;
using System.Collections.Generic;
using System.Web.Mvc;
namespace CURD.Controllers
{
public class UserController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult AddEditUser(UserViewModel model)
{
if (ModelState.IsValid)
{
if (model.Id.HasValue)
{
StaticData.Update(model);
}
else
{
StaticData.Save(model);
}
}
string status = model.Id.HasValue ? "updated" : "saved";
string message = $"User has been { status } successfully!";
return Json(message, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult DeleteUser(int id)
{
StaticData.Delete(id);
string message = $"User has been removed successfully!";
return Json(message, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetAllUsers()
{
List<UserViewModel> users = StaticData.UserList;
return Json(users, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult GetUser(int id)
{
UserViewModel userViewModel = StaticData.Find(id);
return Json(userViewModel, JsonRequestBehavior.AllowGet);
}
}
}
@{
ViewBag.Title = "CURD with angular!";
}
<div ng-controller="userController">
<div class="form-group">
<button type="button" class="btn btn-success" data-target="#addEditUser" data-toggle="modal"><i class="fa fa-plus"> </i> Add New</button>
</div>
<table class="table table-bordered table-condensed table-hover table-responsive">
<thead>
<tr>
<td>Id</td>
<td>Email</td>
<td>First Name</td>
<td>Last Name</td>
<td>Phone</td>
<td>Created Date</td>
<td>Action</td>
</tr>
</thead>
<tr ng-repeat="employee in employees">
<td>{{employee.Id}}</td>
<td>{{employee.Email}}</td>
<td>{{employee.FirstName}}</td>
<td>{{employee.LastName}}</td>
<td>{{employee.Phone}}</td>
<td>{{employee.CreatedDate}}</td>
<td>
<button class="btn btn-xs btn-default" data-target="#addEditUser" data-toggle="modal" ng-click="editUser(employee.Id)"><i class="fa fa-edit"></i></button>
<button class="btn btn-xs btn-danger" ng-click="DeleteUser(employee.Id)"><i class="fa fa-trash"></i></button>
</td>
</tr>
</table>
<div id="addEditUser" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Detail</h4>
</div>
<div class="modal-body">
<input type="hidden" class="form-control" ng-model="id">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" ng-model="email" maxlength="50">
</div>
<div class="form-group">
<label for="firstName">FirstName:</label>
<input type="text" class="form-control" id="firstName" ng-model="firstName" maxlength="100">
</div>
<div class="form-group">
<label for="lastName">LastName:</label>
<input type="text" class="form-control" id="lastName" ng-model="lastName" maxlength="100">
</div>
<div class="form-group">
<label for="phone">Phone:</label>
<input type="text" class="form-control" id="phone" ng-model="phone" maxlength="10">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<button type="submit" class="btn btn-success" ng-click="SaveUser()"><i class="fa fa-save"></i> Submit</button>
</div>
</div>
</div>
</div>
</div>
Now runs the application, the starting page shows user the list and here Add New button available to add new user details.
Now clicking on the Add new button render new modal popup and fill detail and save.
Figure 4: Add User
Conclusion
This article explained the basic details and working process of AngularJs with an example.here we create a usercontroller to perform server side operation and index view is used to bind data with help of AngularJs.
Download
We can download the complete source code from this link: Download
See Also
Here these article are related to AngularJs & MVC: