Tuesday, March 1, 2016

CURD operation using MVC with AgularJS and Entity Framework

       


Here we will create a simple MVC application using AgularJS and Entity Framework to perform CURD operations.

  1. Create a new MVC Application by Opening Visual Studio 2013 --> ASP.NET Web Application ---> MVC template
  2. Add AgularJS from Nuget Package, Right click on project--> select manage Nuget package and search for AgularJS install.
  3. Add a script file in script folder and write your AgularJS code from here.
var myapp = angular.module("myapp", []);
  1. angular.module is the starting point for AgularJS.

ng-app="myapp"> Add this in your cshtml file
  1. Now add Entity Framework to the Project. For this, you need to first right click on the project and click on "Add new item".
  2. Select Data and select ADO.Net Entity Data Model. From here you can add whatever tables you want. For this Application I added a table called 'Tbl_StudentInfo'. Then build your solution.
  3. Retrieve
    Create an object for your entities in controller.
AngularJSDBEntities entity = new AngularJSDBEntities();
Using entity oject we can access the database tables.
Example: var data = entity.Tbl_StudentInfo.ToList();

  1. Go to your js file and write below code.
myapp.factory('StudentService', ['$http', function ($http) {
var StudentService = {};
StudentService.getStudents = function () {
return $http.get('/Student/GetStudents');
};
return StudentService;
}]);



  1. Here we are using a factory service, these methods will interact with the controller.cs.
  2. Write a controller method which will call the StudentService getStudents() method.
myapp.controller("studentInfo", function ($scope, StudentService) {
var Student = {
Id: "",
FristName: "",
LastName: "",
RllNo: "",
ClassName: ""
}
StudentService.getStudents().success(function (res) {
$scope.studentresult = res;
$scope.Action = "Save";
})
});
  1. Go to .html file and write the below script.
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></scr ipt>
<script src="~/Scripts/Student.js"></script>
<div ng-app="myapp">
<div ng-controller="studentInfo">
<table>
<tr>
<td><b>ID</b></td>
<td><b>Frist Name</b></td>
<td><b>Last Name</b></td>
<td><b>Roll No</b></td>
<td><b>Class Name</b></td>
</tr>
<tr ng-repeat="student in studentresult">
<td>
{{student.Id}}
</td>
<td>
{{student.FristName}}
</td>
<td>
{{student.LastName}}
</td>
<td>
{{student.RllNo}}
</td>
<td>
{{student.ClassName}}
</td>
<td>
<span ng-click="GetStudentById(student)">Edit</span>
<span ng-click="Delete(student)">Delete</span>
</td>
</tr>
</table>
  1. Here we are using ng-repeat in order to show the data into a tabular format.
  2. In Controller class and add below code.
AngularJSDBEntities4 entity = new AngularJSDBEntities4();
public JsonResult GetStudents()
{
var data = entity.Tbl_StudentInfo.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
Output:
ID
Frist Name
Last Name
Roll No
Class Name
1
Kutum
Rao
500500
1
Edit Delete
3
Ravi
Kumar
500501
2
Edit Delete
4
Manne
veera
500504
4
Edit Delete
5
Siva
Kumar
500499
7
Edit Delete


  1. Insert a new record
  • Add below method in factory service in your.JS file.
StudentService.addStudent = function (Student) {
// debugger;
var res = $http({
method: "post",
url: '/Student/AddStudent',
data: JSON.stringify(Student),
dataType: "json"

});
return res;
};
  • Add below method in your js controller.
$scope.regStudent = function () {
Student.FristName = $scope.FristName;
Student.LastName = $scope.LastName;
Student.RllNo = $scope.RllNo;
Student.ClassName = $scope.ClassName;
if ($scope.Action == "Save") {
var getData = StudentService.addStudent(Student);
getData.success(function (msg) {
$scope.studentresult = msg;
})
}
}
  • we are passing a student object to 'addStudent' method which is available in StudentService factory. This factory method will pass student object to ‘'addStudent' controller method.
  • Add below code in your .html file.
<table> <tr> <td> <label>FristName</label> </td> <td> <input type="text" ng-model="FristName" /><br /> </td> </tr> <tr> <td> <label>LastName</label> </td> <td> <input type="text" ng-model="LastName" /><br /> </td> </tr>
<tr>
<td><label>RllNo</label></td>
<td><input type="text" ng-model="RllNo" /><br /></td>
</tr>
<tr>
<td><label>ClassName</label></td>
<td><input type="text" ng-model="ClassName" /></td>
</tr>
<tr>
<td>
<button ng-click="reset()">Clear</button>
</td>
<td colspan="2">
<input type="button" class="btnAdd" value={{Action}} ng-click="regStudent()" />
</td>
</tr>
</table>
  • Add below code in Controller.
public ActionResult AddStudent(Tbl_StudentInfo student)
{
if (student!=null)
{
entity.Tbl_StudentInfo.Add(student);
entity.SaveChanges();
}
return RedirectToAction("GetStudents", "Student");
}
  1. Edit
  • Add this new method in factory service
StudentService.getStudentById = function (id) {
var res = $http({
method: "get",
url:
"/Student/GetStudentById",
params: {
id: JSON.stringify(id)
}
})
return res;
}
}
  • Add this method in your .js controller
$scope.GetStudentById = function (stuedent) {
$scope.Action = "Update";
StudentService.getStudentById(stuedent.Id).success(function (data) {
$scope.FristName = data.FristName,
$scope.LastName = data.LastName,
$scope.RllNo = data.RllNo,
$scope.ClassName = data.ClassName;
$scope.Id = data.Id;
});
}


  • Add below code in in your controller.cs file
public JsonResult GetStudentById(int id)
{
var data = entity.Tbl_StudentInfo.Find(id);
return Json(data, JsonRequestBehavior.AllowGet);
}
  • Whenever we click on the edit button respective record data will be populated for editing in the controls.
  • Make changes to the input fields and click on 'Update' button
  • For 'updatestudents' data write below code in your factory service in .JS file.
StudentService.updateStudent = function (Student) {
var res = $http({
method: "post",
url: "/Student/UpdateStudents",
data: JSON.stringify(Student),
dataType: "json"
})
return res;
}
  • JS Controller code: Add below code in your regStudent method's else part
$scope.regStudent = function ()
{
Student.FristName = $scope.FristName;
Student.LastName = $scope.LastName;
Student.RllNo = $scope.RllNo;
Student.ClassName = $scope.ClassName;

if ($scope.Action == "Save") {
var getData = StudentService.addStudent(Student);
getData.success(function (msg) {
$scope.studentresult = msg;
})
}
else {
Student.Id = $scope.Id;
var res = StudentService.updateStudent(Student);
//getStudentList();
res.success(function (msg) {
$scope.studentresult = msg;
})
}
}
  • Controller.cs Code:
public ActionResult UpdateStudents(Tbl_StudentInfo student)
{
if (student != null)
{
var updatedData = entity.Tbl_StudentInfo.Where(x => x.Id == student.Id).FirstOrDefault();
updatedData.FristName = student.FristName;
updatedData.LastName = student.LastName;
updatedData.RllNo = student.RllNo;
updatedData.ClassName = student.ClassName;
entity.SaveChanges();
}

return RedirectToAction("GetStudents", "Student");
}

  1. Delete Code :
  • Add below code in your factory service
StudentService.deleteStudent = function (id) {
var res = $http({
method: "post",
url: "/Student/DeleteStudent",
params: {
id: JSON.stringify(id)
}
})
return res;
}
  • JS Controller Code
$scope.Delete = function (stuedent) {
// debugger;
var data = StudentService.deleteStudent(stuedent.Id);

data.then(function (m) {

})
}
  • Controller.CS code
public ActionResult DeleteStudent(int id)
{
var Sid = entity.Tbl_StudentInfo.Where(x => x.Id == id).FirstOrDefault();
entity.Tbl_StudentInfo.Remove(Sid);
entity.SaveChanges();
return RedirectToAction("GetStudents", "Student");
}