Web API Getting Data from Database in JSON format and UI Angular JS Consuming it

Web API - getting data from database  with Entity Model in JSON format. UI Angular JS consumes the API  and produces the output in a tabular format.

Step 1: Create an ASP.Net MVC4 Web API project.

Step 2: Right Click App Data and create a data base 



Step 3: Right click on the Model and add ADO .net Entity Data Model






   Step 4: Check the selected Tables and Views that needs to be Added

   Step 5 : Right Click on Model and Add a class "Subscribers" (MODEL)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ContactManager.Models
{
    public class Subscribers
    {

        public List<MyTable> getSubscribers(ContactManagerEntities sb)
        {
            try
            {
                if (sb != null)
                {
                    return sb.MyTables.ToList();
                }

                return null;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}

Step 6: Right Click on the controller folder and  Add a controller class with Template as Empty Web API

Code :

using ContactManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace ContactManager.Controllers
{
    public class SubscribersController : ApiController
    {

        public List<MyTable> getSubscribers()
        {
            try
            {
                using (var db = new ContactManagerEntities())
                {
                    Subscribers sb = new Subscribers();
                    return (sb.getSubscribers(db).ToList());
                }

            }
            catch (Exception ex)
            {
                throw;
            }

        }





    }
}

Step 7 : To Solve Cross Domain issues add the following in Web.Config file

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>

Step 8 : Add the below code in Global.aspx file

protected void ConfigureApi(HttpConfiguration config)
        {

            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }

Step 9: Add the below code in RouteConfig.cs file

       public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

Step 10: Add the below Code in WebApiConfig.cs

 public static void Register(HttpConfiguration config)
        {

            

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

            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }


DateBase changes 


Create a Table MyTable

CREATE TABLE [dbo].[MyTable] (
    [Id]             INT           NOT NULL,
    [MailId]         NVARCHAR (80) NOT NULL,
    [SubscriberDate] DATETIME      NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);


select * from MyTable

insert into MyTable values (1,'amit.mazumder@socgen.com','01/12/2016');
insert into MyTable values (2,'mazumder.ami@gmail.com','01/2/2016');
insert into MyTable values (3,'mazumder.ami113@gmail.com','01/5/2016');
insert into MyTable values (4,'prims.algorithm@gmail.com','01/10/2016');
insert into MyTable values (5,'amitonline113@gmail.com','01/11/2016');
insert into MyTable values (6,'thevinins_cir@yahoo.co.in','01/6/2016');


Angular Js.

Controller : Creata a Javascript file getList.js and add the controller MyListCtrl code to it

'use strict'
var app = angular.module("mytodoApp")
.controller("MyListCtrl", function ($scope, $http) {

    $http.get('http://localhost:24871/api/Subscribers').success(function (data) {
        $scope.output = data;
    });


View : create a  Html file GetList.html and add the below code

<div class="container">
    
    
    <div class="form-horizontal">
        <input type="text"  placeholder="Email id" ng-model="id">
        <button class="btn-primary" ng-click="add()"><strong>ADD</strong></button>
    </div>

    <table class="table table-striped">
        <thead class="thead-inverse">
            <th>ID</th>
            <th>Mail ID</th>
            <th>Subscriber Date</th>
            <th>Edit</th>
        </thead>
        <tbody>
        <tr ng-repeat="x in output ">
            <td> {{ x.Id }} </td>
            <td> {{ x.MailId }} </td>
            <td> {{ x.SubscriberDate }} </td>
            <td> <button ng-click="edit()"><strong>EDIT</strong></button></td>
        </tr>
        </tbody>
    </table>
    


</div>

For Routing ,Add the below snippet in the app.js files

        .when('/getlist', {
            templateUrl: 'views/GetList.html',
            controller: 'MyListCtrl'
        })


Full Code :

'use strict';

/**
 * @ngdoc overview
 * @name mytodoApp
 * @description
 * # mytodoApp
 *
 * Main module of the application.
 */
angular
  .module('mytodoApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .when('/mypage',{
        templateUrl:'views/MyPage.html',
        controller: 'MyPageCtrl'
      })
      .when('/myword', {
            templateUrl: 'views/MyWordCtrl.html',
            controller: 'MyWordCtrl'
        })
       .when('/mywordcount',{
        templateUrl:'views/MyWordCountCtrl.html',
        controller:'MyCharCtrl'
       })
        .when('/getlist', {
            templateUrl: 'views/GetList.html',
            controller: 'MyListCtrl'
        })
    
        
      .otherwise({
        redirectTo: '/'
      });
  });

Index.html 

Add-
<script src="scripts/controllers/getList.js"></script>


Full Code

<!doctype html>
<html class="no-js">
  <head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">
    <!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
    <!-- build:css(.) styles/vendor.css -->
    <!-- bower:css -->
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
    <!-- endbower -->
    <!-- endbuild -->
    <!-- build:css(.tmp) styles/main.css -->
    <link rel="stylesheet" href="styles/main.css">
    <!-- endbuild -->
  </head>
  <body ng-app="mytodoApp">
    <!--[if lt IE 7]>
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->

    <!-- Add your site or application content here -->
    <div class="container">
      <div class="header">
        <ul class="nav nav-pills pull-right">
          <li class="active"><a ng-href="#">Home</a></li>
          <li><a ng-href="#/about">About</a></li>
          <li><a ng-href="#">Contact</a></li>
        </ul>
        <h3 class="text-muted">mytodo</h3>
      </div>

      <div ng-view=""></div>

      <div class="footer">
        <p><span class="glyphicon glyphicon-heart"></span> from the Yeoman team</p>
      </div>
    </div>


    <!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
     <script>
       (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
       (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
       m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
       })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

       ga('create', 'UA-XXXXX-X');
       ga('send', 'pageview');
    </script>

    <!--[if lt IE 9]>
    <script src="bower_components/es5-shim/es5-shim.js"></script>
    <script src="bower_components/json3/lib/json3.min.js"></script>
    <![endif]-->

    <!-- build:js(.) scripts/vendor.js -->
    <!-- bower:js -->
    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/json3/lib/json3.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <script src="bower_components/angular-resource/angular-resource.js"></script>
    <script src="bower_components/angular-cookies/angular-cookies.js"></script>
    <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-touch/angular-touch.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <!-- endbower -->
    <!-- endbuild -->

        <!-- build:js({.tmp,app}) scripts/scripts.js -->
        <script src="scripts/app.js"></script>
        <script src="scripts/controllers/main.js"></script>
        <script src="scripts/controllers/about.js"></script>
        <script src="scripts/controllers/mypage.js"></script>
        <script src="scripts/controllers/countWords.js"></script>
        <script src="scripts/controllers/ServiceMyPage.js"></script>
        <script src="scripts/controllers/countChar.js"></script>
        <script src="scripts/controllers/getList.js"></script>
        <!-- endbuild -->
</body>
</html>



Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6