Since we are using EntityFramwork for CRUD operation, so, first, create a table, given below-

Step 1. Create MVC Application
Open Visual Studio
File - New - Project…
Select ASP.NET MVC4/5 Web Application.
Enter the name of Application as "AngularWithMvc".
Click OK.
Step 2. Create the Model
As we know, we will use the EntityFramework, so we will use the .edmx model and will use its entity(Table) as a model. So,
Right click on the Models folder and go to Add. Select Add New Item, given below-

Now, select Data tab from Side menu, choose entity data model and type the name of entity data model, as given below-

Create a controller with the name of “ StudentController”, as given below-

This was the process to create an MVC Application and Entity data model integration. Now, we are going to create a model, Controller and Service to perform the CRUD operation. Thus, create a folder at the root with the name of “AngularScript” and add the “angular.min.js” from the link, given below-
http://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js
Now, create three JavaScript files with the name of “StudentModel”, “StudentService” and “StudentController”, as given below-
Open StudentController.cs (MVC Controller). Create a View with the name of Index and write the code, given below-
Index.cshtml
- @{
- ViewBag.Title = "Index";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
- <h2>Student Details :</h2>
- <div ng-controller="stuCntr">
- <script src="~/scripts/bootstrap.min.js"></script>
- <script src="~/scripts/jquery-1.10.2.min.js"></script>
- <input type="submit" value="Add Student" ng-click="AddNewStudent()" />
- <div id="dvStudnetDetails">
- <table cellpadding="12" class="table table-bordered table-hover">
- <tr>
- <td>
- <b>Id</b>
- </td>
- <td>
- <b>Student Name</b>
- </td>
- <td>
- <b>Address</b>
- </td>
- <td>
- <b>Email</b>
- </td>
- <td>
- <b>Manage</b>
- </td>
- </tr>
- <tr ng-repeat="stu in students">
- <td ng-show="aa">
- {{stu.Id}}
- </td>
- <td>
- {{$index+1}}
- </td>
- <td ng-show="a">
- <input type="text" ng-model="stu.StudentName" />
- </td>
- <td ng-hide="a">
- {{stu.StudentName}}
- </td>
- <td ng-show="a">
- <input type="text" ng-model="stu.StudentAddress" />
- </td>
- <td ng-hide="a">
- {{stu.StudentAddress}}
- </td>
- <td ng-show="a">
- <input type="text" ng-model="stu.StudentEmail" />
- </td>
- <td ng-hide="a">
- {{stu.StudentEmail}}
- </td>
- <td>
- <span ng-hide="a" ng-click="a=!a">Edit</span>
- <span ng-show="a" ng-click="a=!a">Cancel</span>
- <span ng-show="a" ng-click="UpdateStudent(stu)">Update</span>
- <span ng-click="deleteStudent(stu,$index)">Delete</span>
- </td>
- </tr>
- </table>
- </div>
- <div id="dvAddStudnet" ng-show="dvStudent">
- <p class="dvTask">{{Action}} New Student</p>
- <table>
- <tr>
- <td>Name : </td>
- <td>
- <input type="text" id="txtName" ng-model="student.StudentName" />
- </td>
- </tr>
- <tr>
- <td>Email : </td>
- <td>
- <input type="text" id="txtEmail" ng-model="student.StudentEmail" />
- </td>
- </tr>
- <tr>
- <td>Address : </td>
- <td>
- <input type="text" id="txtAddress" ng-model="student.StudentAddress" />
- </td>
- </tr>
- </table>
- <input type="submit" value="Submit" ng-click="AddStudnet(student)" />
- </div>
- </div>
In View, given above, I have created HTML table and bound a data field, using AngularJS directives (ng-model, ng-controller, ng-repeat etc.) and there are also a code form to add new student records (See in dvAddStudnet div). This view contains a controller section only. There are no ng-App in this view. We have written the ng-app directives in layout, which renders all the view, as given below-
_Layout.cshtml
- <!DOCTYPE html>
- <html ng-app="StudnetApp">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title - Angular Js with MVC Demo</title>
- <link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
- <link href="~/Content/bootstrap.min.css" rel="stylesheet" type="text/css" />
- <script src="~/Scripts/modernizr-2.6.2.js"></script> @*Angular liabrary and js used in Application*@
- <script src="~/AngularScricpt/angular.min.js"></script>
- <script src="~/AngularScricpt/StudentModel.js"></script>
- <script src="~/AngularScricpt/StudentService.js"></script>
- <script src="~/AngularScricpt/Studnetcontroller.js"></script>
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button> @Html.ActionLink("AngularJs Demo", "Index", "Student", new { area = "" }, new { @class = "navbar-brand" }) </div>
- <div class="navbar-collapse collapse">
- <ul class="nav navbar-nav"> </ul>
- </div>
- </div>
- </div>
- <div class="container body-content"> @RenderBody()
- <hr />
- <footer>
- <p>© @DateTime.Now.Year - AngularJs with MVC demo</p>
- </footer>
- </div>
- <script src="~/Scripts/jquery-1.10.2.min.js"></script>
- <script src="~/Scripts/bootstrap.min.js"></script>
- </body>
- </html>
Now, open StudentModel.js (in AngularScript folder) and assign the app's name, which you have given in layout page. It is very easy, as you need to just open studentmodel.js and type the name of app, given below-
StudentModel.js
- var app = angular.module("StudnetApp", []);
We are only assigning the module name in this file.
Now, open StudnetController.js and write the code, given below-
StudentController.js
- app.controller("stuCntr", function($scope, StudentService) {
- $scope.dvStudent = false;
- GetStudentList();
- $scope.students = [];
- //To Get All Records
- function GetStudentList() {
- StudentService.getAllStudents().success(function(stu) {
- $scope.students = stu;
- }).error(function() {
- alert('Error in getting records');
- });
- }
- // To display Add div
- $scope.AddNewStudent = function() {
- $scope.Action = "Add";
- $scope.dvStudent = true;
- }
- // Adding New student record
- $scope.AddStudnet = function(student) {
- StudentService.AddNewStudent(student).success(function(msg) {
- $scope.students.push(msg)
- $scope.dvAddStudnet = false;
- }, function() {
- alert('Error in adding record');
- });
- }
- // Deleting record.
- $scope.deleteStudent = function(stu, index) {
- var retval = StudentService.deleteStudent(stu.Id).success(function(msg) {
- $scope.students.splice(index, 1);
- // alert('Student has been deleted successfully.');
- }).error(function() {
- alert('Oops! something went wrong.');
- });
- }
- // Updateing Records
- $scope.UpdateStudent = function(tbl_Student) {
- var RetValData = StudentService.UpdateStudent(tbl_Student);
- getData.then(function(tbl_Student) {
- Id: $scope.Id;
- StudentName: $scope.studentName;
- StudentAddress: $scope.StudentAddress;
- StudentEmail: $scope.StudentEmail;
- }, function() {
- alert('Error in getting records');
- });
- }
- });
In the code, given above, we create a controller and written all CRUD operation code. We also assigned Services, which will invoke the MVC controller to perform the action, as required. (See the controller, Service and all function in the image, given below)-

Now, open StudentService.js file and write the code, given below. Here, View calls the controller, controller calls the Service and Service calls the MVC controller action.
StudentService.js
- app.service("StudentService", function($http) {
- //get All Eployee
- this.getAllStudents = function() {
- return $http.get("Student/GetStudentList");
- };
- // Adding Record
- this.AddNewStudent = function(tbl_Student) {
- return $http({
- method: "post",
- url: "Student/AddStudent",
- data: JSON.stringify(tbl_Student),
- dataType: "json"
- });
- }
- // Updating record
- this.UpdateStudent = function(tbl_Student) {
- return $http({
- method: "post",
- url: "Student/UpdateStudent",
- data: JSON.stringify(tbl_Student),
- dataType: "json"
- });
- }
- // Deleting records
- this.deleteStudent = function(Id) {
- return $http.post('Student/DeleteStudent/' + Id)
- }
- });
Now, open StudentController.cs (MVC controller) and write the code, given below. The code, given below, has all the action from CRUD operation-
StudentController.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using AngularWithMvc.Models;
- namespace AngularWithMvc.Controllers
- {
- public class StudentController: Controller {
- // GET: Student
- public ActionResult Index() {
- return View();
- }
- [HttpPost]
- public JsonResult AddStudent(tbl_Student stu) {
- if (stu != null) {
- using(TestDBEntities dbContext = new TestDBEntities()) {
- dbContext.tbl_Student.Add(stu);
- dbContext.SaveChanges();
- return Json(stu, JsonRequestBehavior.AllowGet);
- }
- } else {
- return Json("Some Error Occured");
- }
- }
- [HttpPost]
- public string UpdateStudent(tbl_Student stu) {
- if (stu != null) {
- using(TestDBEntities dbContext = new TestDBEntities()) {
- tbl_Student lstStudent = dbContext.tbl_Student.Where(x => x.Id == stu.Id).FirstOrDefault();
- lstStudent.StudentName = stu.StudentName;
- lstStudent.StudentAddress = stu.StudentAddress;
- lstStudent.StudentEmail = stu.StudentEmail;
- dbContext.SaveChanges();
- return "Student Updated";
- }
- } else {
- return "Oops! something went wrong.";
- }
- }
- public JsonResult GetStudentList() {
- using(TestDBEntities dbContext = new TestDBEntities()) {
- List < tbl_Student > studentList = dbContext.tbl_Student.ToList();
- return Json(studentList, JsonRequestBehavior.AllowGet);
- }
- }
- [HttpPost]
- public string DeleteStudent(int Id) {
- if (Id != 0) {
- using(TestDBEntities dataContext = new TestDBEntities()) {
- // int id = Convert.ToInt32(Id);
- var lstStud = dataContext.tbl_Student.Where(x => x.Id == Id).FirstOrDefault();
- dataContext.tbl_Student.Remove(lstStud);
- dataContext.SaveChanges();
- return "Student has been deleted succhessfully.";
- }
- } else {
- return " Oops! Error occered.";
- }
- }
- }
- }
Now, press F5 to run the code. I hope, your Browser will display the screen, as shown below-

Kumar BhimsenPosted May 6, 2024, 4:39 PM
Using AutoMapper;using Azure; using IUMS.PRD.API.Middleware; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using System.Text; using UMS.PRD.SERVICES; using UMS.PRD.SERVICES.Model; using UMS.PRD.SERVICES.Models; namespace IUMS.PRD.API.Controllers { [Route("api/[controller]")] [ApiController] public class AuthenticateController : ControllerBase { private readonly IUserManagement _svc; private readonly IRoleMaster _role; //private readonly IMapper _mapper; private readonly IConfiguration _configuration; private readonly ILogger<GlobalExceptionHandlingMiddleware> _logger; public AuthenticateController(IUserManagement svc, IRoleMaster role, IConfiguration configuration, ILogger<GlobalExceptionHandlingMiddleware> logger) { _svc = svc; _role = role; _configuration = configuration; // _mapper = mapper; _logger = logger; } [AllowAnonymous] [HttpPost] [Route("login")] public async Task<IActionResult> GetUser([FromBody] UserLoginModel model) { // try // { var users = await _svc.GetUser(model.Username, model.Password); var USerDetails = users.FirstOrDefault(); if (USerDetails != null) { var userrole = await _svc.GetuserRole(USerDetails.UserId.ToString()); var authClaims = new List<Claim> { new Claim(ClaimTypes.Name, USerDetails.UserName), new Claim(ClaimTypes.Email, USerDetails.Email), new Claim(ClaimTypes.Gender, "M"), new Claim("FULLNAME", USerDetails.Firstname +""+ USerDetails.Lastname), new Claim(ClaimTypes.Surname,"KUMAR"), new Claim("UserId", USerDetails.UserId.ToString()), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), }; foreach (var userRole in userrole) { authClaims.Add(new Claim(ClaimTypes.Role, userRole.UserRoleName)); } var token = CreateToken(authClaims); var refreshToken = GenerateRefreshToken(); _ = int.TryParse(_configuration["JWT:RefreshTokenValidityInDays"], out int refreshTokenValidityInDays); // user.RefreshToken = refreshToken; // user.RefreshTokenExpiryTime = DateTime.Now.AddDays(refreshTokenValidityInDays); return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token), RefreshToken = refreshToken, Expiration = token.ValidTo, Firstname = USerDetails.UserName, Lastname = USerDetails.Lastname, id= USerDetails.UserId, roles=userrole }); } return Unauthorized(); //} //catch //{ // _logger.LogError("Error"); // // throw ex; // return Ok(new Exception { Errorcode = "500", Message = "Error" }); //} } [HttpPost] [Authorize] [Route("register")] public async Task<IActionResult> Register([FromBody] UserManagementModel model) { var result = await _svc.AddUser(model); if (result == -1) return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User already exists!" }); if (result.ToString() == "") return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User creation failed! Please check user details and try again." }); return Ok(new Response { Status = "Success", Message = "User created successfully!" }); } [HttpGet] [Authorize] //[ValidateAntiForgeryToken] [Route("GetAlluser")] public async Task<IActionResult> userAll() { var users = await _svc.GetAllUser(); if (users != null) return Ok(users); return NoContent(); } [HttpGet] [Authorize] [Route("Getrole")] public async Task<IActionResult> GetRole() { var role = await _svc.GetRole(); if (role != null) return Ok(role); return NoContent(); } [HttpGet] [Authorize] [Route("GetUserById/{userid}")] public async Task<IActionResult> GetUserById(string userid) { var users = await _svc.GetById(Convert.ToInt32(userid)); if (users != null) return Ok(users.FirstOrDefault()); return NoContent(); } [HttpPut] [Authorize] [Route("updateuser/{id}")] public async Task<IActionResult> updateuser([FromRoute] int id, [FromBody] UserManagementModel model) { var users = await _svc.updateUser(id, model); if (users != 0) return Ok(users); return NoContent(); } [HttpDelete] [Authorize] [Route("deleteuser/{id}")] public async Task<IActionResult> DeleteUser([FromRoute] int id) { var users = await _svc.delteUser(id); if (users != 0) return Ok(users); return NoContent(); } [HttpPost] [Authorize] [Route("AddRole")] public async Task<IActionResult> Addrole([FromBody] RoleModel model) { var result = await _role.AddRole(model); if (result == -1) return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "Role already exists!" }); if (result.ToString() == "") return StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Message = "User Role failed! Please check user details and try again." }); return Ok(new Response { Status = "Success", Message = "Role created successfully!" }); } [HttpPost] [Authorize] [Route("GetAllrole")] public async Task<IActionResult> GetAllrole() { var users = await _role.Getrole(); if (User != null) return Ok(users); return NoContent(); } [AllowAnonymous] [HttpPost("refresh-token")] public async Task<IActionResult> RefreshToken(UserManagementModel2 tokenModel) { if (tokenModel is null) { return BadRequest("Invalid client request"); } string? accessToken = tokenModel.Token; string? refreshToken = tokenModel.RefreshToken; var principal = GetPrincipalFromExpiredToken(accessToken); if (principal == null) { return BadRequest("Invalid access token or refresh token"); } #pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type. #pragma warning disable CS8602 // Dereference of a possibly null reference. string username = principal.Identity.Name; // Get the claims values var UserId = principal.Claims.Where(c => c.Type == "UserId") .Select(c => c.Value).SingleOrDefault(); var UFullName = principal.Claims.Where(c => c.Type == "FULLNAME") .Select(c => c.Value).SingleOrDefault(); //var sid = principal.Claims.Where(c => c.Type == ClaimTypes.Sid) // .Select(c => c.Value).SingleOrDefault(); #pragma warning restore CS8602 // Dereference of a possibly null reference. #pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type. var users = await _svc.GetById(Convert.ToInt32(UserId)); var user = users.FirstOrDefault(); // var userrole = await _svc.GetuserRole(USerDetails.UserId.ToString()); if (user == null) //|| //user.RefreshToken != refreshToken || user.RefreshTokenExpiryTime <= DateTime.Now) { return BadRequest("Invalid access token or refresh token"); } var newAccessToken = CreateToken(principal.Claims.ToList()); var newRefreshToken = GenerateRefreshToken(); // user.RefreshToken = newRefreshToken; //await _userManager.UpdateAsync(user); //return new ObjectResult(new //{ // accessToken = new JwtSecurityTokenHandler().WriteToken(newAccessToken), // refreshToken = newRefreshToken //}); _ = int.TryParse(_configuration["JWT:TokenValidityInMinutes"], out int tokenValidityInMinutes); return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(newAccessToken), RefreshToken = newRefreshToken, Expiration = DateTime.Now.AddMinutes(tokenValidityInMinutes), Firstname = username, Lastname = UFullName, id = UserId, roles=user.UserRoleModel }); } private JwtSecurityToken CreateToken(List<Claim> authClaims) { var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"])); _ = int.TryParse(_configuration["JWT:TokenValidityInMinutes"], out int tokenValidityInMinutes); var token = new JwtSecurityToken( issuer: _configuration["JWT:ValidIssuer"], audience: _configuration["JWT:ValidAudience"], expires: DateTime.Now.AddMinutes(tokenValidityInMinutes), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return token; } private static string GenerateRefreshToken() { var randomNumber = new byte[64]; using var rng = RandomNumberGenerator.Create(); rng.GetBytes(randomNumber); return Convert.ToBase64String(randomNumber); } private ClaimsPrincipal? GetPrincipalFromExpiredToken(string? token) { var tokenValidationParameters = new TokenValidationParameters { ValidateAudience = false, ValidateIssuer = false, ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"])), ValidateLifetime = false }; var tokenHandler = new JwtSecurityTokenHandler(); var principal = tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken); if (securityToken is not JwtSecurityToken jwtSecurityToken || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase)) throw new SecurityTokenException("Invalid token"); return principal; } } }
Seema ChaudharyPosted Oct 7, 2019, 7:55 AM
Nice Example, with simple steps
Beer SinghPosted Aug 21, 2019, 8:00 AM
Very nice and easy to understand
Pergin SheniPosted Feb 26, 2019, 12:10 AM
Code Downloaded. But I got the same content of this page in word file format. But having Source code in a visual studio would be better.
Pergin SheniPosted Feb 25, 2019, 11:58 PM
Well said! I am expert in MVC Ajax,etc but not in Angular. Thank you. Realy it is nice to learn.
Santosh YadavPosted Oct 31, 2018, 7:15 AM
Code downloaded. but unable to open files.unzip file name as .~lock.AngularJsWithMVC.odt# and AngularJsWithMVC.odt. any one can help
Santosh YadavPosted Oct 31, 2018, 7:14 AM
Code downloaded. but unable to open files
tyne ghiePosted Oct 1, 2018, 7:44 PM
Where did getData come from on you StudentController.js Update?
Vikrant ShekharPosted Nov 6, 2017, 2:22 AM
Nice Article it is useful
Wajid HassanPosted Jul 14, 2017, 9:45 AM
Entity Data Model further description ?
Wajid HassanPosted Jul 14, 2017, 9:44 AM
Can you please put here details for TestDBEntities().....
Ravi PatelPosted Jun 15, 2017, 5:12 AM
Nice article thanks
Prasanna MuraliPosted Sep 5, 2016, 11:07 AM
Nice post......