Angularjs CRUD operation with Asp.net MVC
Create a table in local Sql express with below script,
CREATE TABLE [dbo].[EmployeeDetail] ( [EmployeeId] INT IDENTITY (1, 1) NOT NULL, [EmployeeName] NVARCHAR (MAX) NULL, [Age] INT NOT NULL, CONSTRAINT [PK_dbo.EmployeeDetail] PRIMARY KEY CLUSTERED ([EmployeeId] ASC) ); |
Create a New Asp.net MVC Project in Visual Studio as below,
File –> New Project
Right click on References and Click Manage Nuget Packets.Install AngularJS in Nuget Packet as shown,
Click on Install. AngularJs scripts will be added as shown in Solution explorer.
Add the below code in BundleConfig.cs,
bundles.Add(new ScriptBundle(“~/bundles/angular”).Include( “~/Scripts/angular.js”, “~/Scripts/angular-route.js” )); |
Add the below script reference in _Layouts.cshtml,
@Scripts.Render(“~/bundles/angular”) |
Create a EmployeeModel.cs class in Model with below code,
[Table(“EmployeeDetail”)] public class EmployeeModel { [Key] public int EmployeeId { get; set; } public string EmployeeName { get; set; } public int Age { get; set; } } |
Replace the User context in AccountModels.cs with the below code,
public class UsersContext : DbContext { public UsersContext() : base(“DefaultConnection”) { } public DbSet<UserProfile> UserProfiles { get; set; } public DbSet<EmployeeModel> EmployeeDetails { get; set; } } |
Add EmployeeController class file in Controller Folder and add the below,
namespace angularjsCRUDoperation.Controllers { public class EmployeeController : Controller { private UsersContext db = new UsersContext(); // // GET: /Employee/Index public ActionResult Index() { return View(); } public JsonResult GetEmployee() { return Json(db.EmployeeDetails.ToList(), JsonRequestBehavior.AllowGet); } // // GET: /Employee/Details/5 public ActionResult Details(int id = 0) { EmployeeModel employeedetail = db.EmployeeDetails.Find(id); if (employeedetail == null) { return HttpNotFound(); } return View(employeedetail); } // // GET: /Employee/Create public ActionResult Create() { return View(); } // // POST: /Employee/Create [HttpPost] public string Create1(EmployeeModel employeedetail) { if (ModelState.IsValid) { db.EmployeeDetails.Add(employeedetail); db.SaveChanges(); return “success”; } return “success”; } public ActionResult Edit(string id) { return View(); } // // GET: /Employee/Edit/5 public JsonResult Edit1(string id) { EmployeeModel employeedetail = db.EmployeeDetails.Find(Convert.ToInt32(id)); return Json(employeedetail, JsonRequestBehavior.AllowGet); } // // POST: /Employee/Edit/5 [HttpPost] public string UpdateEmp(EmployeeModel employeedetail) { if (ModelState.IsValid) { db.Entry(employeedetail).State = EntityState.Modified; db.SaveChanges(); return “Success”; } return “Failure”; } // // GET: /Employee/Delete/5 public ActionResult Delete(int id = 0) { EmployeeModel employeedetail = db.EmployeeDetails.Find(id); if (employeedetail == null) { return HttpNotFound(); } return View(employeedetail); } // // POST: /Employee/Delete/5 [HttpPost, ActionName(“Delete”)] [ValidateAntiForgeryToken] public ActionResult DeleteConfirmed(int id) { EmployeeModel employeedetail = db.EmployeeDetails.Find(id); db.EmployeeDetails.Remove(employeedetail); db.SaveChanges(); return RedirectToAction(“Index”); } protected override void Dispose(bool disposing) { db.Dispose(); base.Dispose(disposing); } } } |
Add Employee folder in Views and create Create.cshtml, Edit.cshtml and Index.cshtml as shown below in
Solution Explorer.
Put below code in Create.cshtml,
@{ ViewBag.Title = “Create”; } <h2>Create</h2> @using (Html.BeginForm()) { <div ng-app=”empApp” class=”container”> <div ng-controller=”EmployeeController”> <div> <p class=”divHead”>{{Action}} Employee</p> <table> <tr> <td><b>Id</b></td> <td> <input type=”text” disabled ng-model=”EmployeeId” /> </td> </tr> <tr> <td><b>Name</b></td> <td> <input type=”text” ng-model=”EmployeeName” /> </td> </tr> <tr> <td><b>Age</b></td> <td> <input type=”text” ng-model=”Age” /> </td> </tr> <tr> <td colspan=”2″> <input type=”button” class=”btnAdd” value=”Save” ng-click=”AddUpdateEmployee()” /> </td> </tr> </table> </div> </div> </div> } <div> @Html.ActionLink(“Back to List”, “Index”) </div> @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) @Scripts.Render(“~/employeeclient.js”) } |
Put below code in Edit.cshtml,
@model angularjsCRUDoperation.Models.EmployeeModel @{ ViewBag.Title = “Edit”; } <h2>Edit</h2> @using (Html.BeginForm()) { <div ng-app=”empApp” class=”container”> <div ng-controller=”EditController”> <div> <p class=”divHead”>{{Action}} Employee</p> <table> <tr> <td><b>Id</b></td> <td> <input type=”text” disabled ng-model=”EmployeeId” /> </td> </tr> <tr> <td><b>Name</b></td> <td> <input type=”text” ng-model=”EmployeeName” /> </td> </tr> <tr> <td><b>Age</b></td> <td> <input type=”text” ng-model=”Age” /> </td> </tr> <tr> <td colspan=”2″> <input type=”button” class=”btnAdd” value=”Save” ng-click=”AddUpdateEmployee()” /> </td> </tr> </table> </div> </div> </div> } <div> @Html.ActionLink(“Back to List”, “Index”) </div> @section Scripts { @Scripts.Render(“~/bundles/jqueryval”) @Scripts.Render(“~/employeeclient.js”) } |
Put below code in Index.cshtml,
@{ ViewBag.Title = “Index”; } <h2>Index</h2> <p> @Html.ActionLink(“Create New”, “Create”) </p> @section scripts{ @Scripts.Render(“~/employeeclient.js”) } <div ng-app=”empApp” class=”container”> <br /> <br /> <input type=”text” placeholder=”Search Student” ng-model=”searchEmployee” /> <br /> <div ng-controller=”EmployeeController”> <table class=”table”> <tr> <td>Employee id</td> <td>Employee Name</td> <td> Age </td> </tr> <tr ng-repeat=”r in students | filter : searchEmployee”> <td>{{r.EmployeeId}}</td> <td>{{r.EmployeeName}}</td> <td> {{r.Age}} </td> <td> <input type=”button” ng-click=”editEmployee(r)” class=”btnAdd” value=”Edit” /> </td> </tr> </table> </div> </div> |
Create a js File employeeclient.js in the root of the project and put below code,
var empApp = angular.module(’empApp’, []) empApp.controller(‘EmployeeController’, function ($scope, EmployeeService) { getStudents(); function getStudents() { $scope.students = []; EmployeeService.getStudents() .then(function (studs) { $scope.students = studs.data; } , function (error) { $scope.status = ‘Unable to load customer data: ‘ + error.message; alert(“failure”); console.log($scope.status); }); } $scope.AddUpdateEmployee = function () { debugger; var Employee = { EmployeeId: $scope.EmployeeId, EmployeeName: $scope.EmployeeName, Age: $scope.Age }; var getAction = $scope.Action; var getData = EmployeeService.AddEmp(Employee); getData.then(function (msg) { getStudents(); alert(msg.data); $scope.divEmployee = false; }, function () { alert(‘Error in adding record’); }); } $scope.editEmployee = function (employee) { debugger; window.location.href = ‘/Employee/Edit?id=’ + employee.EmployeeId; } }); empApp.factory(‘EmployeeService’, [‘$http’, function ($http) { var EmployeeService = {}; EmployeeService.getStudents = function () { return $http.get(‘/Employee/GetEmployee’); }; // Add Employee EmployeeService.AddEmp = function (employee) { var response = $http({ method: “post”, url: “/Employee/Create1”, data: JSON.stringify(employee), dataType: “json” }); return response; } return EmployeeService; }]); empApp.controller(‘EditController’, function ($scope, EditService) { var me = getUrlVars()[“id”]; editEmployee(me); function editEmployee(Id) { debugger; // window.location.href = ‘/Employee/Edit?id=’ + Id; var getData = EditService.getEmployee(Id); getData.then(function (emp) { $scope.EmployeeId = emp.data.EmployeeId; $scope.EmployeeName = emp.data.EmployeeName; $scope.Age = emp.data.Age; $scope.Action = “Update”; $scope.divEmployee = true; }, function () { alert(‘Error in getting records’); }); } $scope.AddUpdateEmployee = function () { debugger; var Employee = { EmployeeId: $scope.EmployeeId, EmployeeName: $scope.EmployeeName, Age: $scope.Age }; var getAction = $scope.Action; var getData = EditService.updateEmp(Employee); getData.then(function (msg) { alert(msg.data); $scope.divEmployee = true; }, function () { alert(‘Error in adding record’); }); } }); empApp.factory(‘EditService’, [‘$http’, function ($http) { var EditService = {}; // get Employee By Id EditService.getEmployee = function (employeeID) { var response = $http({ method: “post”, url: “/Employee/Edit1”, params: { id: employeeID } }); return response; } // Update Employee EditService.updateEmp = function (employee) { var response = $http({ method: “post”, url: “/Employee/UpdateEmp”, data: JSON.stringify(employee), dataType: “json” }); return response; } return EditService; }]); // Read a page’s GET URL variables and return them as an associative array. function getUrlVars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf(‘?’) + 1).split(‘&’); for (var i = 0; i < hashes.length; i++) { hash = hashes[i].split(‘=’); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } |
Solution Explorer looks like below,
Run the solution,
OUTPUT as below,
Click below to download the Angularjs crud solution,
https://1drv.ms/u/s!ArddhCoxftkQg9t6X3vBOck_4proJA
Recent Posts
Categories
- All
- Angularjs training in Chennai
- ASP.NET Core
- dot net training
- dot net training in chennai
- dotnet full stack developer
- Free dotnet training
- information on dotnet
- Learn Java in chennai
- Learn Python at Karaikudi
- learn python online
- learn python online from chennai
- Linq Queries in .net
- mutual funds
- MVC Training Tutorials
- PHP Training in Chennai
- pmp training online
- power apps online training
- Python Training Online
- share market
- Sharepoint framework online training
- SharePoint Freelancers in Chennai
- software testing
- spfx online training
- Stock market
- Uncategorized