Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

CRUD, Paging, Sorting, Searching with AngularJS in MVC

5 Oct 2016 2  
This article starts with creating the project in MVC with using the bootstrap classes to give better look to the UI and controls used on UI.

Introduction

When selecting the latest technologies, several factors come into play, including how will these technologies will be integrated with our project. This articles solves the problem for begginer's who start working with AngularJS and MVC. This article tells each and every aspect of the anguarjs to use with, what why and how.

Starting with the database

  • Firstly Create database Named TestData.
  • After creating the database create a table with name Employee,Designation and Department.

  • Set the Id column as primary key and auto increment id.
  • Database work is done here.

Download the requred js and css files from below given links

Be familiar with the things before proceed

  • Module are used to seprate the logics for apllication.
  • var app = angular.module("myApp", ['angularUtils.directives.dirPagination']);
  • Here in the code we declare the application myApp module using angular.module, And in the array we pass the dependent modules, like in this we pass the dependent module for paging.
  • We use the module using ng-app directive in the html page.
  • AngularJS mainly depedent on controllers to control the data and its flow.
  • When the page loads each time the Controller.js file also loads and methods called on load will be executed.
  • The controller contains the objects of javascript containing functions,method and properties.
  • Each controller accepts $scope as a parameter which refers to the application.
  • We use the controller using ng-controller in the html page.
  • Services are the javascript functions that does the certain tasks told by the controller.AngularJs has many inbuilt services like $http,$location,$route,$window.Each service will does specific task.For example : $http is used for ajax call to the server.
  • The method from the controller calls the method from the service .
  • Service deals with the server code and call the action results specified in the ajax url and response back to the service.
  • The service then return response to the controller.js and controller.js deals with the views and displays the data on page.

Start with the Code.

  • Open the VS2012 ,Create New ASP.Net MVC4 Web Application and give the Name BootstrapAngularMvc.
  • Go to Models Folder in the solution explorer of visual studio.
  • Right click the Models folder and find ADD >ADO.NET Entity Data Model. Select ADO.NET Entity Data Model.
  • Provide the name DBModel.After that pop up will appear

  • Select generate from database and click next.

  • In the below given box type entity name as SahilEntities and After that click New connection.

  • Select Sql server authentication and fill the credentials like server name ,user name ,password,and then select your TestData database from the database list.

  • Check the checkboxes of tables and click on finish.
  • After that go to the controller folder and Create EmployeeController.And write code
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using  BootstrapAngularMvc.Models;
    
    namespace  BootstrapAngularMvc.Controllers
    {
    	public class EmployeeController : Controller
    	{
    		public ActionResult Employee()
    		{
    		  return View();
    		}
    		
    		//For getting the all records from database.		
    		 public JsonResult getAll()
    		{
    			using (SahilEntities dataContext = new SahilEntities())
    			{
    				 var employeeList = (from E in dataContext.Employees
    							join dep in dataContext.Departments on E.DepartmentID equals dep.Id
    							join dsg in dataContext.Designations on E.DesignationID equals dsg.Id
    							orderby E.Id
    							select new
    							{
    								E.Id,
    								E.name,
    								E.DOB,
    								E.Gender,
    								E.Email,
    								E.Mobile,
    								E.Address,
    								E.JoiningDate,
    								dep.DepartmentName,
    								E.DepartmentID,
    								dsg.DesignationName,
    								E.DesignationID
    							}).ToList();
    				var JsonResult = Json(employeeList, JsonRequestBehavior.AllowGet);
    				JsonResult.MaxJsonLength = int.MaxValue;
    				return JsonResult;
    			}
    		}
    	}
    }
  • Find RouteConfig.cs in App_Start folder and change the default Controller and Action.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace BootstrapAngularMvc
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Employee", action = "Employee", id = UrlParameter.Optional }
                );
            }
        }
    }
  • Add 3 files --> Module.js,Controller.js,Service.js in content folder.
    In Module.js write the given code.

    var app = angular.module("myApp", []);

    In Controller.js write the given code .		
    	app.controller("myCntrl", function ($scope, myService) {		
    		GetAllEmployees();        
    		
    		//For sorting according to columns
    		$scope.sort = function (keyname) {
    			$scope.sortKey = keyname;
    			$scope.reverse = !$scope.reverse;
    		}
    		
    		//To Get All Records  
    		function GetAllEmployees() {
    			var getData = myService.getEmployees();
    
    			getData.then(function (emp) {
    				$scope.employees = emp.data;  							
    			}, function (emp) {
    			alert("Records gathering failed!");
    			});
    		}
    	});
    In Service.js write the given code.
    app.service("myService", function ($http) {
    
    	//get All Employee
    	this.getEmployees = function () {			   
    		return $http.get("/Employee/getAll");
    	};
    });
  • Right click the Employee Action of the EmployeeController and select AddView option.

  • Add a view and see the code from below given link.
  • See View.cshtml file here.

Starts with paging

  • Download DirPagination.js and save in the content folder of project.
  • Update the code in Module.js.
    var app = angular.module("myApp", ['angularUtils.directives.dirPagination']);

Change CSS

  • Find site.css in content folder and change the background colour to "#fff" in html,body,body of main content.

Starts with CRUD operations with AngularJS

  • Add the code in Employee Controller.
  • First method in below given code use Class Employee as Parameter to get the data from view via controller.js
  • Second method use EmployeeID as parameter that from the row that is clicked.
  • Again update method also take the Employee class as a parameter and update the record that is edited.
  • Other 2 methods fill the dropdownlists for designations and departments.
                                                       <-- Employee record insertion code  -->
    public string AddEmployee(Employee Emp)
    {
       if (Emp != null)
       {
           using (SahilEntities dataContext = new SahilEntities())
           {
               Employee employee = new Employee();
               employee.name = Emp.name;
               employee.DOB = Convert.ToDateTime(Emp.DOB).ToString("yyyy/MM/dd");
               employee.Gender = Emp.Gender;
               employee.Email = Emp.Email;
               employee.Mobile = Emp.Mobile;
               employee.Address = Emp.Address;
               employee.JoiningDate = Convert.ToDateTime(Emp.JoiningDate).ToString("yyyy/MM/dd");
               employee.DepartmentID = Emp.DepartmentID;
               employee.DesignationID = Emp.DesignationID;
               dataContext.Employees.Add(employee);
               dataContext.SaveChanges();
               return "Employee added Successfully";
           }
       }
       else
       {
           return "Addition of Employee unsucessfull !";
       }
    }
    
                                                       <-- Get Employee by ID -->
    public JsonResult getEmployeeByNo(string EmpNo)
    {
       try
       {
           using (SahilEntities dataContext = new SahilEntities())
           {
               int no = Convert.ToInt32(EmpNo);
               var employeeList = dataContext.Employees.Find(no);
               return Json(employeeList, JsonRequestBehavior.AllowGet);
           }
       }
       catch (Exception exp)
       {
           return Json("Error in getting record !", JsonRequestBehavior.AllowGet);
       }
    
    }
    
                                                   <-- Employee record updation code -->
    public string UpdateEmployee(Employee Emp)
    {
       if (Emp != null)
       {
           using (SahilEntities dataContext = new SahilEntities())
           {
               int no = Convert.ToInt32(Emp.Id);
               var employeeList = dataContext.Employees.Where(x => x.Id == no).FirstOrDefault();
               employeeList.name = Emp.name;
               employeeList.DOB = Convert.ToDateTime(Emp.DOB).ToString("yyyy/MM/dd");
               employeeList.Gender = Emp.Gender;
               employeeList.Email = Emp.Email;
               employeeList.Mobile = Emp.Mobile;
               employeeList.Address = Emp.Address;
               employeeList.JoiningDate = Convert.ToDateTime(Emp.JoiningDate).ToString("yyyy/MM/dd");
               employeeList.DepartmentID = Emp.DepartmentID;
               employeeList.DesignationID = Emp.DesignationID;
               dataContext.SaveChanges();
               return "Employee Updated Successfully";
           }
       }
       else
       {
           return "Invalid Employee";
       }
    }
    
                                                   <-- Bind dropdownlist of designations -->
    public JsonResult GetDesignations()
    {
       using (SahilEntities context = new SahilEntities())
       {
           var desg = context.Designations.ToList();
           return Json(desg, JsonRequestBehavior.AllowGet);
       }
    }
    
                                                   <-- Bind dropdownlist of departments -->
    public JsonResult GetDepartments()
    {
       using (SahilEntities data = new SahilEntities())
       {
           var deps = data.Departments.ToList();
           return Json(deps, JsonRequestBehavior.AllowGet);
       }
    }
    
  • Write code in Controller.js i.e. given below.
  • In controllers $scope is used to linkbetween the controller and view.It is a glue between the application controller and view.In controllers we pass value to the $scope and used in View with ng-bind or {{}}.
  • AddEmployeeDiv opens the modal popup for adding the employee and fill the dropdowns for designation and department.
  • alertmsg shows message after the data saved or updated or any error occured during save operation.
  • EditEmployee method calls the method from service to edit the record.
  • Based on action of edit or add AddUpdateEmployee method calls the service method for insertion or deletion of employee.
  • ClearFields method serves the purpose of make the texboxes empty after any operation.
    											<-- This is used to open popup for adding record. -->
    
    $scope.AddEmployeeDiv = function () {
    	ClearFields();
    	$scope.Action = "Add";
    	GetDepartments();
    	GetDesignations();
    }
    											<-- Alert Popup for save ,update messages . -->
     $scope.alertmsg = function () {
            $("#alertModal").modal('hide');
    };
    
    											<-- Bind dropdownlist for designation. -->
    
    function GetDesignations() {
    	var desg = myService.GetDesignations();
    
    	desg.then(function (dsg) {
    	$scope.designations = dsg.data;
    	}, function (dsg) {
    		$("#alertModal").modal('show');
    		$scope.msg = "Error in filling designation drop down !";
    	});
    }
    
    											<-- Bind dropdownlist for department. -->
    function GetDepartments() {
    	var departments = myService.GetDepartment();
    
    	departments.then(function (dep) {
    		$scope.departments = dep.data;
    	}, function (dep) {
    		$("#alertModal").modal('show');
    		$scope.msg = "Error in filling departments drop down !";
    	});
    }
    
    												<-- Get the employee By ID. -->
    $scope.editEmployee = function (employee) {
    	debugger;
    	GetDesignations();
    	GetDepartments();
    	var getData = myService.getEmployee(employee.Id);
    	getData.then(function (emp) {
    		$scope.employee = emp.data;
    		$scope.employeeId = employee.Id;
    		$scope.employeeName = employee.name;
    		$scope.employeeDOB = new Date(employee.DOB);
    		$scope.employeeGender = employee.Gender;
    		$scope.employeeEmail = employee.Email;
    		$scope.employeeMobile = employee.Mobile;
    		$scope.employeeAddress = employee.Address;
    		$scope.employeeJoiningDate = employee.JoiningDate;
    		$scope.employeeDepartment = employee.DepartmentID;
    		$scope.employeeDesignation = employee.DesignationID;
    		$scope.Action = "Edit";
    		$("#myModal").modal('show');
    	},
    	function (msg) {
    		$("#alertModal").modal('show');
    		$scope.msg = msg.data;
    	});
    }
    
    											<-- Insertion and updation code. --> 
    $scope.AddUpdateEmployee = function () {
    	var Employee = {
    		Name: $scope.employeeName,
    		DOB: $scope.employeeDOB,
    		Gender: $scope.employeeGender,
    		Email: $scope.employeeEmail,
    		Mobile: $scope.employeeMobile,
    		Address: $scope.employeeAddress,
    		JoiningDate: $scope.employeeJoiningDate,
    		DepartmentID: $scope.employeeDepartment,
    		DesignationID: $scope.employeeDesignation
    	};
    
    	var getAction = $scope.Action;
    
    	if (getAction == "Edit") {
    		Employee.Id = $scope.employeeId;
    		var getData = myService.updateEmp(Employee);
    		getData.then(function (msg) {
    			GetAllEmployee();
    			ClearFields();
    			$("#alertModal").modal('show');
    			$scope.msg = msg.data;
    		}, function (msg) {
    			$("#alertModal").modal('show');
    			$scope.msg = msg.data;
    		});
    	}
    	else {
    		var getData = myService.AddEmp(Employee);
    		getData.then(function (msg) {
    			GetAllEmployee();
    			$("#alertModal").modal('show');
    			$scope.msg = msg.data;
    			ClearFields();
    
    		}, function (msg) {
    			$("#alertModal").modal('show');
    			$scope.msg = msg.data;
    		});
    	}
    	debugger;
    	GetAllEmployee();
    	$scope.refresh();
    }
    
    											<-- Clear fields after save -->
    										
    function ClearFields() {
    	$scope.employeeId = "";
    	$scope.employeeName = "";
    	$scope.employeeDOB = "";
    	$scope.employeeGender = "";
    	$scope.employeeEmail = "";
    	$scope.employeeMobile = "";
    	$scope.employeeAddress = "";
    	$scope.employeeJoiningDate = "";
    	$scope.employeeDepartment = "";
    	$scope.employeeDesignation = "";
    }
  • Start writing code in Service.js
  • In service we use $http to call the server code and passing the data/parameters in any format we want .we pass the data in json format and get the data in json format.
  • AddEmp method calls the AddEmployee method on the server with data from the View.
  • getEmployee Method calls the getEmployeeByNo method on server for edit the record.
  • Update method calls the UpdateEmployee method on the server for updation operation.
  • And other 2 method calls the server for binding drop down lists.
    											<-- Calls Add Employee method on server -->
    this.AddEmp = function (employee) {
    	var response = $http({
    		method: "post",
    		url: "/Employee/AddEmployee",
    		data: JSON.stringify(employee),
    		dataType: "json"
    	});
    	return response;
    }
    
    										<-- Calls get Employee By Id method on server -->
    this.getEmployee = function (employeeID) {
    	var response = $http({
    		method: "post",
    		url: "/Employee/getEmployeeByNo",
    		params: {
    			id: JSON.stringify(employeeID)
    		}
    	});
    	return response;
    }
    
    										<--Calls the update method on server -->
    this.updateEmp = function (employee) {
    	var response = $http({
    		method: "post",
    		url: "/Employee/UpdateEmployee",
    		data: JSON.stringify(employee),
    		dataType: "json"
    	});
    	return response;
    }
    									<-- Calls the method on server for Designation dropdownlist -->
    this.GetDesignations = function () {
    	return $http.get("/Employee/GetDesignations");
    };
    
    									<-- Calls the method on server for Department dropdownlist --> 
    this.GetDepartment = function () {
    	return $http.get("/Employee/GetDepartments");
    };
  • See Employee.cshtml code from here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here