CRUD operation using AngularJS and WebAPI in ASP.NET WebForm

In this article I will show you how easy it is to consume the WebAPI using AngularJS. To achieve that we are going to create Customer web page where we can do CRUD and filter on List of Customers. Here’s what it look like.
webapi angularjs

For This webpage we need to create ASP.NET WebAPI and AngularJS script to fetch WebAPI data.

Create Customer ASP.NET WebAPI

We are using WebAPI which I created in this article.

Getting Started with Web Form and WebAPI using Entity Framework 5

AngularJS script

How we fetch WebAPI data?
The $http service is a core Angular service that facilitates communication with the remote HTTP servers. This article we are using $http methods to call WebAPI. You can also use $resource instead on $http.

Define CustomerApp and Factory

var app = angular.module('customerApp', []);
        var url = 'api/Customers/';	
	app.factory('customerFactory', function ($http) {
            return {
                getCustomer: function () {
                    return $http.get(url);
                },
                addCustomer: function (customer) {
                    return $http.post(url, customer);
                },
                deleteCustomer: function (customer) {
                    return $http.delete(url + customer.CustomerID);
                },
                updateCustomer: function (customer) {
                    return $http.put(url + customer.Id, customer);
                }
            };
        });

CustomersController
In this controller script we going to use “customerFactory” to do CRUD on Customer Data.

app.controller('CustomersController', function PostsController($scope, customerFactory) {
            $scope.customers = [];
            $scope.loading = true;
            $scope.addMode = false;
 
            $scope.toggleEdit = function () {
                this.customer.editMode = !this.customer.editMode;
            };
            $scope.toggleAdd = function () {
                $scope.addMode = !$scope.addMode;
            };
            $scope.save = function () {
                $scope.loading = true;
                var cust = this.customer;
                customerFactory.updateCustomer(cust).success(function (data) {
                    alert("Saved Successfully!!");
                    cust.editMode = false;
                    $scope.loading = false;
                }).error(function (data) {
                    $scope.error = "An Error has occured while Saving customer! " + data.ExceptionMessage;
                    $scope.loading = false;
 
                });
            };
 
            // add Customer
            $scope.add = function () {
                $scope.loading = true;
                customerFactory.addCustomer(this.newcustomer).success(function (data) {
                    alert("Added Successfully!!");
                    $scope.addMode = false;
                    $scope.customers.push(data);
                    $scope.loading = false;
                }).error(function (data) {
                    $scope.error = "An Error has occured while Adding customer! " + data.ExceptionMessage;
                    $scope.loading = false;
 
                });
            };
            // delete Customer
            $scope.delcustomer = function () {
                $scope.loading = true;
                var currentCustomer = this.customer;
                customerFactory.deleteCustomer(currentCustomer).success(function (data) {
                    alert("Deleted Successfully!!");
                    $.each($scope.customers, function (i) {
                        if ($scope.customers[i].CustomerID === currentCustomer.CustomerID) {
                            $scope.customers.splice(i, 1);
                            return false;
                        }
                    });
                    $scope.loading = false;
                }).error(function (data) {
                    $scope.error = "An Error has occured while Saving customer! " + data.ExceptionMessage;
                    $scope.loading = false;
 
                });
            };
 
            //get all Customers
            customerFactory.getCustomer().success(function (data) {
                $scope.customers = data;
                $scope.loading = false;
            })
            .error(function (data) {
                $scope.error = "An Error has occured while loading posts! " + data.ExceptionMessage;
                $scope.loading = false;
            });
 
        });

Full Page Code:

<!DOCTYPE html>
<html data-ng-app="customerApp">
<head>
    <title>Customer App | AshishBlog</title>
    <script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <link type="text/css" href="http://twitter.github.io/bootstrap/assets/css/bootstrap.css" rel="stylesheet" />
    <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>
</head>
<body>  
    <div data-ng-controller="CustomersController" class="container">
        <h2>Customers</h2>
        <strong class="error">{{ error }}</strong>
        <div id="mydiv" data-ng-show="loading">
            <img src="Images/482.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="addCustomer" data-ng-show="addMode" style="width: 600px; margin: 0px auto;">
            <label>Name:</label><input type="text" data-ng-model="newcustomer.Name" required />
            <label>Email:</label><input type="email" data-ng-model="newcustomer.Email" required />
            <br />          
            <span class="error" data-ng-show="addCustomer.$error.email">Invalid Email format!</span>
            <br />
            <input type="submit" value="Add" data-ng-click="add()" data-ng-disabled="!addCustomer.$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>
                <th>Name</th>
                <th>Email</th>
                <th></th>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="text" data-ng-model="search.Name" /></td>
                <td>
                    <input type="text" data-ng-model="search.Email" /></td>
                <td></td>
            </tr>
 
            <tr data-ng-repeat="customer in customers | filter:search">
                <td><strong data-ng-hide="customer.editMode">{{ customer.CustomerID }}</strong></td>
                <td>
                    <p data-ng-hide="customer.editMode">{{ customer.Name }}</p>
                    <p data-ng-show="customer.editMode">
                        <input type="text" data-ng-model="customer.Name" />
                    </p>
                </td>
                <td>
                    <p data-ng-hide="customer.editMode">{{ customer.Email }}</p>
                    <input data-ng-show="customer.editMode" type="text" data-ng-model="customer.Email" /></td>
                <td>
                    <p data-ng-hide="customer.editMode"><a data-ng-click="toggleEdit(customer)" href="javascript:;">Edit</a> | <a data-ng-click="delcustomer(customer)" href="javascript:;">Delete</a></p>
                    <p data-ng-show="customer.editMode"><a data-ng-click="save(customer)" href="javascript:;">Save</a> | <a data-ng-click="toggleEdit(customer)" href="javascript:;">Cancel</a></p>
                </td>
            </tr>
        </table>
        <hr />
    </div>
   <script src="app.js"></script>
</body>
</html>

Thanks

Getting Started with Web Form and WebAPI using Entity Framework 5

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

In this article, we will use Web API with Empty Web Forms application for CURD on list of Customer Information. We will be using Visual Studio 2012 and .Net 4.5.

Create Empty Web Forms application

Open Visual Studio 2012, Go To New -> Project. Select Visual C# -> Web from the left hand navigation and select project type as ASP.Net Web Forms Application. Enter the project name as AB_CustomerWebAPI

1

Model

Right Click the Project in the Solution Explorer, Select Add -> New Folder from the Context Menu. The name of the class will be “Model”. Then do it again to add class “Customer” under Model Folder
2_

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
namespace AB_CustomerWebAPI.Model
{
    public class Customer
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int CustomerID { get; set; }
        [StringLength(100)]
        public string Name { get; set; }
        [StringLength(100)]
        public string Email { get; set; }
    }
}

DbContext

Right Click the Model Folder in the Solution Explorer, Select Add -> Class from the Context Menu. The name of the class will be “CustomerContext”.

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace AB_CustomerWebAPI_1.Model
{
    public class CustomerContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }
    }
}

Database Connection string

add following line to web.config file of project

<add name="CustomerContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;" providerName="System.Data.SqlClient" />

The Repository

Right Click the Model Folder in the Solution Explorer, Select Add -> Class from the Context Menu. The name of the class will be “CustomerRepository”.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
namespace AB_CustomerWebAPI.Model
{
    public interface ICustomerRepository
    {
        IEnumerable<Customer> GetAll();
        Customer Get(int id);
        Customer Add(Customer item);
        void Remove(int id);
        bool Update(Customer item);
    }
    public class CustomerRepository  : ICustomerRepository
    {
        private readonly CustomerContext _db;
        public CustomerRepository()
        {
            _db = new CustomerContext();
        }
        public IEnumerable<Customer> GetAll()
        {
            return _db.Customers;
        }
        public Customer Get(int id)
        {
            return _db.Customers.Find(id);
        }
        public Customer Add(Customer customer)
        {
            _db.Customers.Add(customer);
            _db.SaveChanges();
            return customer;
        }
        public void Remove(int id)
        {
            Customer customer = _db.Customers.Find(id);
            _db.Customers.Remove(customer);
            _db.SaveChanges();
        }
        public bool Update(Customer item)
        {
            Customer newCustomer =_db.Customers.Find(item.CustomerID);
            if (newCustomer == null)
                return false;
            newCustomer.Email = item.Email;
            newCustomer.Name = item.Name;
            _db.SaveChanges();
            return true;
        }
    }
}

The WebAPI Controller

Right Click the Project in the Solution Explorer, Select Add -> New Folder from the Context Menu. The name of the class will be “Api”. Then do it again to add class “CustomersController” under Api Folder
web api

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AB_CustomerWebAPI.Model;
namespace AB_CustomerWebAPI.Api
{
    public class CustomersController : ApiController
    {
        private static readonly ICustomerRepository _customers = new CustomerRepository();
        // GET api/<controller>
        public IEnumerable<Customer> Get()
        {
            return _customers.GetAll();
        }
        // GET api/<controller>/5
        public Customer Get(int id)
        {
            Customer c = _customers.Get(id);
            if (c == null)
                throw new HttpResponseException(HttpStatusCode.NotFound);

            return c;
        }
        // POST api/<controller>
        public Customer Post(Customer customer)
        {
            return _customers.Add(customer);
        }
        // PUT api/<controller>/5
        public Customer Put(Customer customer)
        {
            if (!_customers.Update(customer))
                throw new HttpResponseException(HttpStatusCode.NotFound);
            return customer;
        }
        // DELETE api/<controller>/5
        public Customer Delete(int id)
        {
            Customer c = _customers.Get(id);
            _customers.Remove(id);
            return c;
        }
    }
}

Adding Web API Route in Global.asax

For the controller to handle requests of a particular type, we will have to define a route in the Global.asax file.
Open global.asax file and add the following code in the “Application_Start” method

void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterOpenAuth();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = System.Web.Http.RouteParameter.Optional }
            );
        }

Now run Web Form Application (F5)

The URL will be something like http://localhost:xxxxx/Default.aspx where xxxxx will be port number.

To Test the WebAPI, we will have to use the URL as defined in the Route. Enter the following URL in the browser http://localhost:xxxxx/api/Customers/ (Replace xxxxx with your port number)

Now database created in your Solution Explorer (App_Data/Database.mdf)
web api

Add some data to Customer table
web api

WebAPI with jQuery (CURD)

Get all Customers:

Web Api URL: api/Customers

web api

    <h3>Get All Customers</h3>
    <input type="button" id="GetallCustomer" value="Display All Customer" />
    <ul id="Customers">
    </ul>
    <hr />

 

 $('#GetallCustomer').click(function (e) {
            e.preventDefault();
            GetAllCustomers();
        });
function GetAllCustomers() {
            jQuery.support.cors = true;
            $.ajax({
                url: '/api/Customers',
                type: 'GET',
                dataType: 'json',
                success: function (customers) {
                    $('#Customers').html('');
                    $.each(customers, function (index, customer) {
                        $('#Customers').append('<li>(' + customer.CustomerID + ') Name=' + customer.Name + ' Email=' + customer.Email + '</li>');
                    });

                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }

Search Customer:

Web Api URL: api/Customers/id

web api

    <h3>Get by CustomerID</h3>
    <input id="txtCustomerID" type="text" /><input id="getCustomer" type="button" value="Get Customer by ID" />
    <ul id="Customer">
    </ul>
    <hr />

 

 $('#getCustomer').click(function (e) {
            e.preventDefault();
            GetCustomer();
        });
  function GetCustomer() {
            jQuery.support.cors = true;
            var id = $('#txtCustomerID').val();
            if (id.length) {
                $('#Customer').html('');
                $.ajax({
                    url: 'api/Customers/' + id,
                    type: 'GET',
                    dataType: 'json',
                    success: function (customer) {
                        $('#Customer').html('<li>(' + customer.CustomerID + ') Name=' + customer.Name + ' Email=' + customer.Email + '</li>');
                    },
                    error: function (x, y, z) {
                        $('#Customer').html(z);
                        alert(x + '\n' + y + '\n' + z);
                    }
                });
            }
            else { $('#Customer').html('enter CustomerID'); }
        }

Add Customer:
web api

   <h3>New Customer</h3>
    <br />
    <input id="txtName" type="text" placeholder="Name" /><br />
    <input id="txtEmail" type="text" placeholder="Email" /><br />
    <input id="Btn_Add" type="button" value="Add" />
    <ul id="NewCustomer">
    </ul>
    <hr />

 

  $('#Btn_Add').click(function (e) {
            e.preventDefault();
            AddCustomer();
        });
 function AddCustomer() {
            jQuery.support.cors = true;
            var customer = {
                Name: $('#txtName').val(),
                Email: $('#txtEmail').val()
            };
            $.ajax({
                url: 'api/Customers',
                type: 'POST',
                data: JSON.stringify(customer),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    $('#NewCustomer').html('<li>(' + data.CustomerID + ') Name=' + data.Name + ' Email=' + data.Email + '</li>');
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }

Delete Customer:

Web Api URL: api/Customers

web api

    <h3>Delete Customer</h3>
    <input id="txtCustID" type="text" /><input id="deleteCustomer" type="button" value="Delete Customer by ID" />
    <ul id=" deleteCustomerDetail">
    </ul>
    <hr />

 

 $('#deleteCustomer').click(function (e) {
            e.preventDefault();
            DeleteEmployee();
        });

  function DeleteEmployee() {
            jQuery.support.cors = true;
            var id = $('#txtCustID').val()
            $.ajax({
                url: 'api/Customers/' + id,
                type: 'DELETE',
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    if (data.CustomerID == id) $('#deleteCustomerDetail').html("Customer ID " + id + " deleted!!");
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }

Update Customer:
web api

   <h3>Update Customer</h3>
    <br />
    <input id="CID" type="text" placeholder="Customer ID" /><br />
    <input id="Name" type="text" placeholder="Name" /><br />
    <input id="Email" type="text" placeholder="Email" /><br />
    <input id="updateCustomer" type="button" value="update" />
    <ul id="UpdateCustomerDetail">
    </ul>
    <hr />

 

$('#updateCustomer').click(function (e) {
            e.preventDefault();
            updateCustomer();
        });
 function updateCustomer() {
            jQuery.support.cors = true;
            var customer = {
                CustomerID: $('#CID').val(),
                Name: $('#Name').val(),
                Email: $('#Email').val()
            };

            $.ajax({
                url: 'api/Customers',
                type: 'PUT',
                data: JSON.stringify(customer),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    $('#UpdateCustomerDetail').html('<li>(' + data.CustomerID + ') Name=' + data.Name + ' Email=' + data.Email + '</li>');
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }

In the “Default.aspx” file, we will use the following code for the body section to display the data


    <h3>Get All Customers</h3>
    <input type="button" id="GetallCustomer" value="Display All Customer" />
    <ul id="Customers">
    </ul>
    <hr />
    <h3>Get by CustomerID</h3>
    <input id="txtCustomerID" type="text" /><input id="getCustomer" type="button" value="Get Customer by ID" />
    <ul id="Customer">
    </ul>
    <hr /></pre>
<h3>New Customer</h3>
<pre>
    <input id="txtName" type="text" placeholder="Name" />
    <input id="txtEmail" type="text" placeholder="Email" />
    <input id="Btn_Add" type="button" value="Add" /></pre>
<ul id="NewCustomer"></ul>

<hr />

<h3>Delete Customer</h3>
<pre>
    <input id="txtCustID" type="text" /><input id="deleteCustomer" type="button" value="Delete Customer by ID" /></pre>
<ul id="deleteCustomerDetail"></ul>

<hr />

<h3>Update Customer</h3>
<pre>
    <input id="CID" type="text" placeholder="Customer ID" />
    <input id="Name" type="text" placeholder="Name" />
    <input id="Email" type="text" placeholder="Email" />
    <input id="updateCustomer" type="button" value="update" /></pre>
<ul id="UpdateCustomerDetail"></ul>

<hr />

<pre><script type="text/javascript">// <![CDATA[
        $('#GetallCustomer').click(function (e) {
            e.preventDefault();
            GetAllCustomers();
        });
        $('#getCustomer').click(function (e) {
            e.preventDefault();
            GetCustomer();
        });
        $('#Btn_Add').click(function (e) {
            e.preventDefault();
            AddCustomer();
        });
        $('#deleteCustomer').click(function (e) {
            e.preventDefault();
            DeleteEmployee();
        });
        $('#updateCustomer').click(function (e) {
            e.preventDefault();
            updateCustomer();
        });
        function GetAllCustomers() {
            jQuery.support.cors = true;
            $.ajax({
                url: '/api/Customers',
                type: 'GET',
                dataType: 'json',
                success: function (customers) {
                    $('#Customers').html('');
                    $.each(customers, function (index, customer) {
                        $('#Customers').append('
	<li>(' + customer.CustomerID + ') Name=' + customer.Name + ' Email=' + customer.Email + '</li>

');
                    });

                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }
        function GetCustomer() {

            jQuery.support.cors = true;
            var id = $('#txtCustomerID').val();
            if (id.length) {
                $('#Customer').html('');
                $.ajax({
                    url: 'api/Customers/' + id,
                    type: 'GET',
                    dataType: 'json',
                    success: function (customer) {
                        $('#Customer').html('
	<li>(' + customer.CustomerID + ') Name=' + customer.Name + ' Email=' + customer.Email + '</li>

');
                    },
                    error: function (x, y, z) {
                        $('#Customer').html(z);
                        alert(x + '\n' + y + '\n' + z);
                    }
                });
            }
            else { $('#Customer').html('enter CustomerID'); }
        }
        function AddCustomer() {
            jQuery.support.cors = true;
            var customer = {
                Name: $('#txtName').val(),
                Email: $('#txtEmail').val()
            };

            $.ajax({
                url: 'api/Customers',
                type: 'POST',
                data: JSON.stringify(customer),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    $('#NewCustomer').html('
	<li>(' + data.CustomerID + ') Name=' + data.Name + ' Email=' + data.Email + '</li>

');
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }

        function DeleteEmployee() {
            jQuery.support.cors = true;
            var id = $('#txtCustID').val()

            $.ajax({
                url: 'api/Customers/' + id,
                type: 'DELETE',
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    if (data.CustomerID == id) $('#deleteCustomerDetail').html("Customer ID " + id + " deleted!!");

                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }
        function updateCustomer() {
            jQuery.support.cors = true;
            var customer = {
                CustomerID: $('#CID').val(),
                Name: $('#Name').val(),
                Email: $('#Email').val()
            };

            $.ajax({
                url: 'api/Customers',
                type: 'PUT',
                data: JSON.stringify(customer),
                contentType: "application/json;charset=utf-8",
                success: function (data) {
                    $('#UpdateCustomerDetail').html('
	<li>(' + data.CustomerID + ') Name=' + data.Name + ' Email=' + data.Email + '</li>

');
                },
                error: function (x, y, z) {
                    alert(x + '\n' + y + '\n' + z);
                }
            });
        }

// ]]></script>

Thanks