CRUD Operations in MVC 5 Using WebAPI With AngularJS

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

Getting Started

  • Start Visual Studio 2013
  • Create a new Project
  • Select Web Template and select ASP.NET Web Application
  • Provide the name and location of website
  • Click "Next"
  • Now select MVC template and do check Web API to add folder and core references.

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 { getset; }  
  6.     public string FirstName { getset; }  
  7.     public string LastName { getset; }  
  8.     public string Address { getset; }  
  9.     public string City { getset; }  
  10.     public string PostalCode { getset; }  
  11.     public string Country { getset; }  
  12.     public string Notes { getset; }  

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 { getset; }  

Now add a controller in the controller directory.

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

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

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

Up Next
    Ebook Download
    View all
    Learn
    View all