CRUD Operation In AngularJS

Introduction

AngularJS is an MVC based framework developed and managed by Google. It is an open source project so anyone can use it. We are going to use AngularJS version 1.6 for developing this application. As we all know that AngularJS is faster than jQuery and it also supports two-way data binding.

Features of AngularJS

  • Two-way data binding
  • Dependency injection
  • Model View Controller
Prerequisites
  • Basic knowledge of ASP.NET MVC5
  • AngularJS
  • Linq

Things you must know before proceeding further

  • ng-app which represents an AngularJS application
  • ng-controller which represents an AngularJS controller
  • ng-model which binds the data with HTML controls
  • ng-repeat is like for each loop in C#

We are going to use Code First Approach so you must have knowledge of Entity Framework. If not then you can refer our Blog which explains the Code First Approach

Now let’s begin

Add the connection string in the Web.Config file present at the root

<connectionStrings>
    <add name="StringDBContext" connectionString="Server=TheCodeHubs-PC;Initial Catalog=DemoDB;Persist Security Info=False;User ID=sa;Password=******;MultipleActiveResultSets=True;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
  </connectionStrings>

Now create the Context class in the Models folder.

using System.Data.Entity;

namespace AngularDemo.Models
{
    public class Context : DbContext
    {
        public Context():base("StringDBContext") {}
        public DbSet<Angular> Angulars { get; set; }
    }
}

Now create the table as Angular in the Models folder.

using System.ComponentModel.DataAnnotations;

namespace AngularDemo.Models
{
    public class Angular
    {
        [Key]
        public int Id {get;set;}
        public string Name { get; set; }
        public string Phone { get; set; }
    }
}

Now add the View in View -> Home -> Index.cshtml

@{
    ViewBag.Title = "Home Page";
    Layout = null;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<div class="container">
    <div ng-app="appModule" ng-controller="appController">
        <h2>CRUD Operation</h2>
        <input type="hidden" ng-model="Id" />
        <div class="form-group">
            <label for="Name">Name</label>
            <input type="text" required class="form-control" ng-model="Name">
        </div>
        <div class="form-group">
            <label for="Phone">Phone:</label>
            <input type="text" required class="form-control" ng-model="Phone">
        </div>
        <button ng-click="save()" ng-disabled="SaveData" class="btn btn-primary">Save Data</button>
        <button ng-click="editSave()" ng-disabled="Editable" class="btn btn-primary">Edit Data</button>

        <hr />
        <table class="table table-hover table-striped" ng-init="getData()">
            <tr>
                <th>Name</th>
                <th>Phone</th>
                <th>Edit</th>
                <th>Delete</th>
            </tr>
            <tr data-ng-repeat="x in crud">
                <td>{{ x.Name }}</td>
                <td>{{ x.Phone }}</td>
                <td>
                    <button class="btn" ng-click="Edit( x.Id )"><i class="fa fa-edit"></i></button>
                </td>
                <td>
                    <button class="btn" ng-click="Delete( x.Id )"><i class="fa fa-trash"></i></button>
                </td>
            </tr>
        </table>
    </div>
</div>
<script>
    var app = angular.module("appModule", []);
    app.controller("appController", function ($scope, $http) {
        $scope.SaveData = false;
        $scope.Editable = true;
        $scope.getData = function () {
            $http({
                method: 'POST',
                url: '/Home/GetData',
            }).then(function (data) {
                $scope.crud = data.data;
            });
        }
        $scope.Edit = function (id) {
            var data = {
                Id: id,
            };
            $http({
                method: 'POST',
                url: '/Home/EditData',
                data: data,
                dataType: "json",
            }).then(function (data) {
                $scope.Name = data.data.Name;
                $scope.Phone = data.data.Phone;
                $scope.Id = data.data.Id;
                $scope.SaveData = true;
                $scope.Editable = false;
            });
        }
        $scope.Delete = function (id) {
            var data = {
                Id: id,
            };
            $http({
                method: 'POST',
                url: '/Home/Delete',
                data: data,
                dataType: "json",
            }).then(function (data) {
                alert("Data deleted successfully");
                $scope.Name = "";
                $scope.Phone = "";
                $scope.getData();
            });
        }
        $scope.save = function () {
            var data = {
                Name: $scope.Name,
                Phone: $scope.Phone
            };
            $http({
                method: 'POST',
                url: '/Home/Index',
                data: data,
                dataType: "json",
            }).then(function (data) {
                if (data.data.success) {
                    alert("Data Inserted Successfully");
                    $scope.Name = "";
                    $scope.Phone = "";
                    $scope.getData();
                } else {
                    alert("Something went wrong");
                }
            });
        }

        $scope.editSave = function () {
            var data = {
                Name: $scope.Name,
                Phone: $scope.Phone,
                Id : $scope.Id
            };
            $http({
                method: 'POST',
                url: '/Home/Editsave',
                data: data,
                dataType: "json",
            }).then(function (data) {
                if (data.data.success) {
                    alert("Data Edited Successfully");
                    $scope.getData();
                    $scope.SaveData = false;
                    $scope.Editable = true;
                    $scope.Name = "";
                    $scope.Phone = "";
                    $scope.Id = "";
                } else {
                    alert("Something went wrong");
                }
            });
        }
    });
</script>

Now finally the code for the HomeController.

using AngularDemo.Models;
using System.Linq;
using System.Web.Mvc;

namespace AngularDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string Name, string Phone)
        {
            int rate = 0;
            Context _context = new Context();
            Angular angular = new Angular(){
                Name=Name,
                Phone=Phone
            };
            _context.Angulars.Add(angular);
            rate=_context.SaveChanges();
            if(rate==1) return Json(new { success = true, JsonRequestBehavior.AllowGet });
            else return Json(new { success = false, JsonRequestBehavior.AllowGet });
        }

        [HttpPost]
        public ActionResult GetData()
        {
            Context _context = new Context();
            return Json(  _context.Angulars.ToList(), JsonRequestBehavior.AllowGet );
        }

        [HttpPost]
        public ActionResult EditData(int Id)
        {
            Context _context = new Context();
            return Json(_context.Angulars.Where(x=>x.Id==Id).FirstOrDefault(), JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public ActionResult Editsave(string Name, string Phone,int Id)
        {
            Context _context = new Context();
            Angular angular = _context.Angulars.FirstOrDefault(x => x.Id == Id);
            angular.Name = Name;
            angular.Phone = Phone;
            _context.Entry(angular).State = System.Data.Entity.EntityState.Modified;
            _context.SaveChanges();
            return Json(new { success = true, JsonRequestBehavior.AllowGet });
        }
        [HttpPost]
        public ActionResult Delete(int Id)
        {
            Context _context = new Context();
            Angular angular = _context.Angulars.FirstOrDefault(x => x.Id == Id);
            _context.Entry(angular).State = System.Data.Entity.EntityState.Deleted;
            _context.SaveChanges();
            return Json(new { success = true, JsonRequestBehavior.AllowGet });
        }
    }
}

You can download this demo from here.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories