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.
Now add a new model class in the model directory.
- public class Friend
- {
- [Key]
- [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
- public int FriendId { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public string Address { get; set; }
- public string City { get; set; }
- public string PostalCode { get; set; }
- public string Country { get; set; }
- public string Notes { get; set; }
- }
Now add a context class.
- public class FriendsContext : DbContext
- {
- public FriendsContext()
- : base("name=DefaultConnection")
- {
- base.Configuration.ProxyCreationEnabled = false;
- }
- public DbSet<Friend> Friends { get; set; }
- }
Now add a controller in the controller directory.
- public class FriendController : ApiController
- {
- private FriendsContext db = new FriendsContext();
-
-
- [HttpGet]
- public IEnumerable<Friend> Get()
- {
- return db.Friends.AsEnumerable();
- }
-
- public Friend Get(int id)
- {
- Friend friend = db.Friends.Find(id);
- if (friend == null)
- {
- throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
- }
-
- return friend;
- }
-
- public HttpResponseMessage Post(Friend friend)
- {
- if (ModelState.IsValid)
- {
- db.Friends.Add(friend);
- db.SaveChanges();
-
- HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, friend);
- response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = friend.FriendId }));
- return response;
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- }
-
- public HttpResponseMessage Put(int id, Friend friend)
- {
- if (!ModelState.IsValid)
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
-
- if (id != friend.FriendId)
- {
- return Request.CreateResponse(HttpStatusCode.BadRequest);
- }
-
- db.Entry(friend).State = EntityState.Modified;
-
- try
- {
- db.SaveChanges();
- }
- catch (DbUpdateConcurrencyException ex)
- {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
- }
-
- return Request.CreateResponse(HttpStatusCode.OK);
- }
-
- public HttpResponseMessage Delete(int id)
- {
- Friend friend = db.Friends.Find(id);
- if (friend == null)
- {
- return Request.CreateResponse(HttpStatusCode.NotFound);
- }
-
- db.Friends.Remove(friend);
-
- try
- {
- db.SaveChanges();
- }
- catch (DbUpdateConcurrencyException ex)
- {
- return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
- }
-
- return Request.CreateResponse(HttpStatusCode.OK, friend);
- }
- protected override void Dispose(bool disposing)
- {
- db.Dispose();
- base.Dispose(disposing);
- }
- }
Now add AngularJS using Manage Nuget Package Manager and search AngularJS.
Now add a new JavaScript file in the scripts directory and add angular functions.
- function friendController($scope, $http) {
- $scope.loading = true;
- $scope.addMode = false;
-
-
- $http.get('/api/Friend/').success(function (data) {
- $scope.friends = data;
- $scope.loading = false;
- })
- .error(function () {
- $scope.error = "An Error has occured while loading posts!";
- $scope.loading = false;
- });
-
- $scope.toggleEdit = function () {
- this.friend.editMode = !this.friend.editMode;
- };
- $scope.toggleAdd = function () {
- $scope.addMode = !$scope.addMode;
- };
-
-
- $scope.save = function () {
- alert("Edit");
- $scope.loading = true;
- var frien = this.friend;
- alert(emp);
- $http.put('/api/Friend/', frien).success(function (data) {
- alert("Saved Successfully!!");
- emp.editMode = false;
- $scope.loading = false;
- }).error(function (data) {
- $scope.error = "An Error has occured while Saving Friend! " + data;
- $scope.loading = false;
-
- });
- };
-
-
- $scope.add = function () {
- $scope.loading = true;
- $http.post('/api/Friend/', this.newfriend).success(function (data) {
- alert("Added Successfully!!");
- $scope.addMode = false;
- $scope.friends.push(data);
- $scope.loading = false;
- }).error(function (data) {
- $scope.error = "An Error has occured while Adding Friend! " + data;
- $scope.loading = false;
-
- });
- };
-
-
- $scope.deletefriend = function () {
- $scope.loading = true;
- var friendid = this.friend.FriendId;
- $http.delete('/api/Friend/' + friendid).success(function (data) {
- alert("Deleted Successfully!!");
- $.each($scope.friends, function (i) {
- if ($scope.friends[i].FriendId === friendid) {
- $scope.friends.splice(i, 1);
- return false;
- }
- });
- $scope.loading = false;
- }).error(function (data) {
- $scope.error = "An Error has occured while Saving Friend! " + data;
- $scope.loading = false;
-
- });
- };
-
- }
Now open the _Layout.cshtml page from the Shared folder and add these two lines to render AngularJS and empjs in the application.
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
- @Scripts.Render("~/bundles/angularjs")
- @Scripts.Render("~/bundles/empjs")
Now let's work on the View.
- @{
- ViewBag.Title = "FriendView";
- Layout = "~/Views/Shared/_Layout.cshtml";
- }
-
- <h2>Friends View</h2>
- <style>
- #mydiv {
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- z-index: 1000;
- background-color: grey;
- opacity: .8;
- }
-
- .ajax-loader {
- position: absolute;
- left: 50%;
- top: 50%;
- margin-left: -32px;
- margin-top: -32px;
- display: block;
- }
- </style>
- <div data-ng-app data-ng-controller="friendController" class="container">
- <strong class="error">{{ error }}</strong>
- <div id="mydiv" data-ng-show="loading">
- <img src="Images/ajax-loader.gif" class="ajax-loader" />
- </div>
- <p data-ng-hide="addMode"><a data-ng-click="toggleAdd()" href="javascript:;" class="btn btn-primary">Add New</a></p>
- <form name="addFriend" data-ng-show="addMode" style="width:600px;margin:0px auto;">
- <label>FirstName:</label><input type="text" data-ng-model="newfriend.FirstName" required />
- <label>LastName:</label><input type="text" data-ng-model="newfriend.LastName" required />
- <label>Address:</label><input type="text" data-ng-model="newfriend.Address" required />
- <label>City:</label><input type="text" data-ng-model="newfriend.City" required />
- <label>PostalCode:</label><input type="text" data-ng-model="newfriend.PostalCode" required />
- <label>Country:</label><input type="text" data-ng-model="newfriend.Country" required />
- <label>Notes:</label><input type="text" data-ng-model="newfriend.Notes" required />
- <br />
- <br />
- <input type="submit" value="Add" data-ng-click="add()" data-ng-disabled="!addFriend.$valid" class="btn btn-primary" />
- <input type="button" value="Cancel" data-ng-click="toggleAdd()" class="btn btn-primary" />
- <br /><br />
- </form>
- <table class="table table-bordered table-hover" style="width:800px">
- <tr>
- <th>#</th>
- <td>FirstName</td>
- <th>LastName</th>
- <th>Address</th>
- <th>City</th>
- <th>PostalCode</th>
- <th>Country</th>
- <th>Notes</th>
- </tr>
-
- <tr data-ng-repeat="friend in friends">
- <td><strong data-ng-hide="friend.editMode">{{ friend.FriendId }}</strong></td>
- <td>
- <p data-ng-hide="friend.editMode">{{ friend.FirstName }}</p>
- <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.FirstName" />
- </td>
- <td>
- <p data-ng-hide="friend.editMode">{{ friend.LastName }}</p>
- <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.LastName" />
- </td>
- <td>
- <p data-ng-hide="friend.editMode">{{ friend.Address }}</p>
- <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Address" />
- </td>
- <td>
- <p data-ng-hide="friend.editMode">{{ friend.City }}</p>
- <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.City" />
- </td>
- <td>
- <p data-ng-hide="friend.editMode">{{ friend.PostalCode }}</p>
- <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.PostalCode" />
- </td>
- <td>
- <p data-ng-hide="friend.editMode">{{ friend.Country }}</p>
- <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Country" />
- </td>
- <td>
- <p data-ng-hide="friend.editMode">{{ friend.Notes }}</p>
- <input data-ng-show="friend.editMode" type="text" data-ng-model="friend.Notes" />
- </td>
- <td>
- <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>
- <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>
- </td>
- </tr>
- </table>
- <hr />
-
- </div>
Run the application to see the output:
Click on the Add New Button:
Click on the edit link:
For more information download the attached sample.
ConclusionIn 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.