- Getting Started AngularJS
- Looping With Ng-repeat in AngularJS
- ngController in AngularJS
- Filtering Data in AngularJS
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();
- // GET api/<controller>
- [HttpGet]
- public IEnumerable<Friend> Get()
- {
- return db.Friends.AsEnumerable();
- }
- // GET api/<controller>/5
- public Friend Get(int id)
- {
- Friend friend = db.Friends.Find(id);
- if (friend == null)
- {
- throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
- }
- return friend;
- }
- // POST api/<controller>
- 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);
- }
- }
- // PUT api/<controller>/5
- 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);
- }
- // DELETE api/<controller>/5
- 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;
- //Used to display the data
- $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;
- };
- //Used to save a record after edit
- $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;
- });
- };
- //Used to add a new record
- $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;
- });
- };
- //Used to edit a record
- $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; /* -1 * image width / 2 */
- margin-top: -32px; /* -1 * image height / 2 */
- 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>

Click on the Add New Button:

Click on the edit link:

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.

emad elshareefPosted Mar 4, 2017, 2:25 PM
Error in ViewStart what is ViewBag ????
kalu singh raoPosted Jul 16, 2016, 3:11 AM
Nice...
StepUpPosted Mar 5, 2016, 4:56 AM
Guys, "Edit" is not working. How can I resolve it?
Naren BanarasePosted Feb 25, 2016, 1:45 AM
Nice Artical..... But I got one issue. alert(emp); (what is emp?) emp.editMode = false;(Not Working)
Akash VarshneyPosted Oct 3, 2015, 11:17 AM
good to know about empjs .. !! nice ..
Astro BoyzonePosted Feb 4, 2015, 2:31 AM
{{ error }} is being displayed on top of the view , what might be the issue?
Former memberPosted Dec 20, 2014, 7:56 AM
I really love this article. Anyways, I just want to know that you are using Web Api so is it possible to work MVC controller with views, using Entity Framework with AngularJS?
Anh Nhan RaPosted Nov 25, 2014, 2:46 AM
Please help me . Argument 'friendController' is not a function, got undefined
Manish SharmaPosted Nov 21, 2014, 1:26 AM
Hi all, update your action and remove int id from put like : "public HttpResponseMessage Put(Friend friend)" and add "int id = friend.FriendId;" in your action than it will be work for you.
Munna KumarPosted Oct 28, 2014, 4:06 AM
Save feature not working please reply what is this error and how to resolve at [email protected]
jeya prakashPosted Oct 24, 2014, 2:59 AM
it is very needed at this time. Useful article
bhupender khatkarPosted Oct 8, 2014, 11:09 PM
Save Not working
mekh eddinePosted Sep 8, 2014, 12:00 PM
This works for me,check the connection string in the web.config
Devansh KumarPosted Sep 5, 2014, 10:44 AM
Save functionality not working. There was an error occurs which is "The requested resource does not support http method 'PUT'.".please reply what is this error and how to resolve at [email protected]
GrishmaPosted Aug 9, 2014, 2:22 AM
Hi, i have created web api project with controller for crud operations. Now i need to use that web api in another web project , i need to know how can i access web api in web project.
Rajeev RanjanPosted Jul 17, 2014, 1:33 AM
Dear sir, i was also trying to make a webapi and consuming all get,post,put,delete methods in html page using jQuery. Will you help me sir coz i couldn't able to use put,delete and post calls. how to call put,delete calls using jQuery
Raj KumarPosted Jun 23, 2014, 2:33 AM
I need to check this.
minhhung voPosted Jun 22, 2014, 8:46 PM
save feature isn't work
Sanjay KumarPosted Jun 21, 2014, 1:26 AM
Nice article
Ruben FlorezPosted Jun 20, 2014, 10:14 AM
Nice article. Almost everything its clear. Can you explain us a bit more about the (empjs). What's its role there ?