Before proceeding further I recommend reading my previous angularJS articles, so that you can understand AngularJS very well.

Getting Started

MVC template

Now add a new model class in the model directory.

  1. public class Friend
  2. {
  3. [Key]
  4. [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
  5. public int FriendId { get; set; }
  6. public string FirstName { get; set; }
  7. public string LastName { get; set; }
  8. public string Address { get; set; }
  9. public string City { get; set; }
  10. public string PostalCode { get; set; }
  11. public string Country { get; set; }
  12. public string Notes { get; set; }
  13. }

Now add a context class.

  1. public class FriendsContext : DbContext
  2. {
  3. public FriendsContext()
  4. : base("name=DefaultConnection")
  5. {
  6. base.Configuration.ProxyCreationEnabled = false;
  7. }
  8. public DbSet<Friend> Friends { get; set; }
  9. }

Now add a controller in the controller directory.

  1. public class FriendController : ApiController
  2. {
  3. private FriendsContext db = new FriendsContext();
  4. // GET api/<controller>
  5. [HttpGet]
  6. public IEnumerable<Friend> Get()
  7. {
  8. return db.Friends.AsEnumerable();
  9. }
  10. // GET api/<controller>/5
  11. public Friend Get(int id)
  12. {
  13. Friend friend = db.Friends.Find(id);
  14. if (friend == null)
  15. {
  16. throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
  17. }
  18. return friend;
  19. }
  20. // POST api/<controller>
  21. public HttpResponseMessage Post(Friend friend)
  22. {
  23. if (ModelState.IsValid)
  24. {
  25. db.Friends.Add(friend);
  26. db.SaveChanges();
  27. HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, friend);
  28. response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = friend.FriendId }));
  29. return response;
  30. }
  31. else
  32. {
  33. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  34. }
  35. }
  36. // PUT api/<controller>/5
  37. public HttpResponseMessage Put(int id, Friend friend)
  38. {
  39. if (!ModelState.IsValid)
  40. {
  41. return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
  42. }
  43. if (id != friend.FriendId)
  44. {
  45. return Request.CreateResponse(HttpStatusCode.BadRequest);
  46. }
  47. db.Entry(friend).State = EntityState.Modified;
  48. try
  49. {
  50. db.SaveChanges();
  51. }
  52. catch (DbUpdateConcurrencyException ex)
  53. {
  54. return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
  55. }
  56. return Request.CreateResponse(HttpStatusCode.OK);
  57. }
  58. // DELETE api/<controller>/5
  59. public HttpResponseMessage Delete(int id)
  60. {
  61. Friend friend = db.Friends.Find(id);
  62. if (friend == null)
  63. {
  64. return Request.CreateResponse(HttpStatusCode.NotFound);
  65. }
  66. db.Friends.Remove(friend);
  67. try
  68. {
  69. db.SaveChanges();
  70. }
  71. catch (DbUpdateConcurrencyException ex)
  72. {
  73. return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
  74. }
  75. return Request.CreateResponse(HttpStatusCode.OK, friend);
  76. }
  77. protected override void Dispose(bool disposing)
  78. {
  79. db.Dispose();
  80. base.Dispose(disposing);
  81. }
  82. }

Now add AngularJS using Manage Nuget Package Manager and search AngularJS.

search AngularJS

Now add a new JavaScript file in the scripts directory and add angular functions.

  1. function friendController($scope, $http) {
  2. $scope.loading = true;
  3. $scope.addMode = false;
  4. //Used to display the data
  5. $http.get('/api/Friend/').success(function (data) {
  6. $scope.friends = data;
  7. $scope.loading = false;
  8. })
  9. .error(function () {
  10. $scope.error = "An Error has occured while loading posts!";
  11. $scope.loading = false;
  12. });
  13. $scope.toggleEdit = function () {
  14. this.friend.editMode = !this.friend.editMode;
  15. };
  16. $scope.toggleAdd = function () {
  17. $scope.addMode = !$scope.addMode;
  18. };
  19. //Used to save a record after edit
  20. $scope.save = function () {
  21. alert("Edit");
  22. $scope.loading = true;
  23. var frien = this.friend;
  24. alert(emp);
  25. $http.put('/api/Friend/', frien).success(function (data) {
  26. alert("Saved Successfully!!");
  27. emp.editMode = false;
  28. $scope.loading = false;
  29. }).error(function (data) {
  30. $scope.error = "An Error has occured while Saving Friend! " + data;
  31. $scope.loading = false;
  32. });
  33. };
  34. //Used to add a new record
  35. $scope.add = function () {
  36. $scope.loading = true;
  37. $http.post('/api/Friend/', this.newfriend).success(function (data) {
  38. alert("Added Successfully!!");
  39. $scope.addMode = false;
  40. $scope.friends.push(data);
  41. $scope.loading = false;
  42. }).error(function (data) {
  43. $scope.error = "An Error has occured while Adding Friend! " + data;
  44. $scope.loading = false;
  45. });
  46. };
  47. //Used to edit a record
  48. $scope.deletefriend = function () {
  49. $scope.loading = true;
  50. var friendid = this.friend.FriendId;
  51. $http.delete('/api/Friend/' + friendid).success(function (data) {
  52. alert("Deleted Successfully!!");
  53. $.each($scope.friends, function (i) {
  54. if ($scope.friends[i].FriendId === friendid) {
  55. $scope.friends.splice(i, 1);
  56. return false;
  57. }
  58. });
  59. $scope.loading = false;
  60. }).error(function (data) {
  61. $scope.error = "An Error has occured while Saving Friend! " + data;
  62. $scope.loading = false;
  63. });
  64. };
  65. }

Now open the _Layout.cshtml page from the Shared folder and add these two lines to render AngularJS and empjs in the application.

  1. @Scripts.Render("~/bundles/jquery")
  2. @Scripts.Render("~/bundles/bootstrap")
  3. @Scripts.Render("~/bundles/angularjs")
  4. @Scripts.Render("~/bundles/empjs")

Now let's work on the View.

  1. @{
  2. ViewBag.Title = "FriendView";
  3. Layout = "~/Views/Shared/_Layout.cshtml";
  4. }
  5. <h2>Friends View</h2>
  6. <style>
  7. #mydiv {
  8. position: absolute;
  9. top: 0;
  10. left: 0;
  11. width: 100%;
  12. height: 100%;
  13. z-index: 1000;
  14. background-color: grey;
  15. opacity: .8;
  16. }
  17. .ajax-loader {
  18. position: absolute;
  19. left: 50%;
  20. top: 50%;
  21. margin-left: -32px; /* -1 * image width / 2 */
  22. margin-top: -32px; /* -1 * image height / 2 */
  23. display: block;
  24. }
  25. </style>
  26. <div data-ng-app data-ng-controller="friendController" class="container">
  27. <strong class="error">{{ error }}</strong>
  28. <div id="mydiv" data-ng-show="loading">
  29. <img src="Images/ajax-loader.gif" class="ajax-loader" />
  30. </div>
  31. <p data-ng-hide="addMode"><a data-ng-click="toggleAdd()" href="javascript:;" class="btn btn-primary">Add New</a></p>
  32. <form name="addFriend" data-ng-show="addMode" style="width:600px;margin:0px auto;">
  33. <label>FirstName:</label><input type="text" data-ng-model="newfriend.FirstName" required />
  34. <label>LastName:</label><input type="text" data-ng-model="newfriend.LastName" required />
  35. <label>Address:</label><input type="text" data-ng-model="newfriend.Address" required />
  36. <label>City:</label><input type="text" data-ng-model="newfriend.City" required />
  37. <label>PostalCode:</label><input type="text" data-ng-model="newfriend.PostalCode" required />
  38. <label>Country:</label><input type="text" data-ng-model="newfriend.Country" required />
  39. <label>Notes:</label><input type="text" data-ng-model="newfriend.Notes" required />
  40. <br />
  41. <br />
  42. <input type="submit" value="Add" data-ng-click="add()" data-ng-disabled="!addFriend.$valid" class="btn btn-primary" />
  43. <input type="button" value="Cancel" data-ng-click="toggleAdd()" class="btn btn-primary" />
  44. <br /><br />
  45. </form>
  46. <table class="table table-bordered table-hover" style="width:800px">
  47. <tr>
  48. <th>#</th>
  49. <td>FirstName</td>
  50. <th>LastName</th>
  51. <th>Address</th>
  52. <th>City</th>
  53. <th>PostalCode</th>
  54. <th>Country</th>
  55. <th>Notes</th>
  56. </tr>
  57. <tr data-ng-repeat="friend in friends">
  58. <td><strong data-ng-hide="friend.editMode">{{ friend.FriendId }}</strong></td>
  59. <td>
  60. <p data-ng-hide="friend.editMode">{{ friend.FirstName }}</p>
  61. <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.FirstName" />
  62. </td>
  63. <td>
  64. <p data-ng-hide="friend.editMode">{{ friend.LastName }}</p>
  65. <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.LastName" />
  66. </td>
  67. <td>
  68. <p data-ng-hide="friend.editMode">{{ friend.Address }}</p>
  69. <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Address" />
  70. </td>
  71. <td>
  72. <p data-ng-hide="friend.editMode">{{ friend.City }}</p>
  73. <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.City" />
  74. </td>
  75. <td>
  76. <p data-ng-hide="friend.editMode">{{ friend.PostalCode }}</p>
  77. <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.PostalCode" />
  78. </td>
  79. <td>
  80. <p data-ng-hide="friend.editMode">{{ friend.Country }}</p>
  81. <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Country" />
  82. </td>
  83. <td>
  84. <p data-ng-hide="friend.editMode">{{ friend.Notes }}</p>
  85. <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Notes" />
  86. </td>
  87. <td>
  88. <p data-ng-hide="friend.editMode"><a data-ng-click="toggleEdit(friend)" href="javascript:;">Edit</a> | <a data-ng-click="deletefriend(friend)" href="javascript:;">Delete</a></p>
  89. <p data-ng-show="friend.editMode"><a data-ng-click="save(friend)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(friend)" href="javascript:;">Cancel</a></p>
  90. </td>
  91. </tr>
  92. </table>
  93. <hr />
  94. </div>
Run the application to see the output:

output

Click on the Add New Button:

edit link

Click on the edit link:

New Button

For more information download the attached sample.

Conclusion

In this article we have learned how to do CRUD operations in MVC 5 using the Web API and AngularJS. If you have any question or comments then put a line in the c-sharcorner comments section.