Web API and Angular Js and JSON
Web Api
Controller:
----------------------------------
using ContactManager.Models;
using ContactManager.Service;
//using System.Web.Http.Cors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ContactManager.Controllers
{
// [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class ContactController : ApiController
{
private ContactRepository cntrepo;
public ContactController()
{
this.cntrepo = new ContactRepository();
}
public string Get()
{
return cntrepo.GetAllContacts();
}
       
}
}
                
        
   
    
Controller:
----------------------------------
using ContactManager.Models;
using ContactManager.Service;
//using System.Web.Http.Cors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ContactManager.Controllers
{
// [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class ContactController : ApiController
{
private ContactRepository cntrepo;
public ContactController()
{
this.cntrepo = new ContactRepository();
}
public string Get()
{
return cntrepo.GetAllContacts();
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Model
----------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ContactManager.Models
{
    public class Contact
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
}
--------------------------------------------------------------------------------------------------------------------------
ControllerRepository
----------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ContactManager.Models;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Serialization;
namespace ContactManager.Service
{
    public class ContactRepository
    {
        private const string CacheKey = "ContactStore";
        public ContactRepository()
        {
            var ctx = HttpContext.Current;
            if (ctx != null)
            {
                if (ctx.Cache[CacheKey] == null)
                {
                    var contact = new Contact[]{
                        new Contact
                                {
                                Id=4,
                                Name="Mohan"
                                },
                        new Contact
                                {
                                Id=5,
                                Name="Manoj"
                                },
                        new Contact
                                {
                                Id=6,
                                Name="Manav"
                                },
                        new Contact
                                {
                                Id=7,
                                Name="Mohit"
                                }
                    };
                    ctx.Cache[CacheKey] = contact;
                }
            }
        }
        public string GetAllContacts()
        {
            //var ctx = HttpContext.Current;
            //if (ctx != null)
            //{
            //    return (Contact[])ctx.Cache[CacheKey];
            //}
            //return new Contact[]
            //{
            //    new Contact
            //    {
            //        Id=0,
            //        Name= "Placeholder"
            //    }
            //};
            String cs = ConfigurationManager.ConnectionStrings["DBConn"].ConnectionString;
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection(cs))
            {
                using (SqlCommand cmd = new SqlCommand("Select * from Contact", conn))
                {
                    conn.Open();
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    List<Dictionary<string, object>> rows= new List<Dictionary<string, object>>();
                    Dictionary<string, object> row;
                    foreach (DataRow dr in dt.Rows)
                    {
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dt.Columns)
                            {
                            row.Add(col.ColumnName, dr[col]);
                            }
                            rows.Add(row);
                    }
                    return serializer.Serialize(rows);
                }
            }
        }
    }
}
--------------------------------------------------------------------------------------------------------------------------
Web.Config
----------------------------------
Conncetion String
<connectionStrings>
    <add name="DBConn" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\Apotheosis\Documents\Visual Studio 2012\Projects\1-clickPublish\1-clickPublish\App_Data\1-ClickPublish.mdf';Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient"/>
  </connectionStrings>
CORS issue
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
--------------------------------------------------------------------------------------------------------------------------
WebApi.Config
----------------------------------
Converting default XML to JSON data
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
--------------------------------------------------------------------------------------------------------------------------
Controller.js - getList.js
----------------------------------
'use strict'
var app = angular.module("mytodoApp")
.controller("MyListCtrl", function ($scope, $http) {
  $http.get('http://localhost:24871/api/contact').success(function (data) {
      $scope.output = JSON.parse(data)
  });
}
);
HTML 
----------------------------------
<div class="container">
    <table>
        <tr ng-repeat="x in output track by $index">
            <td> {{ x.ID }} </td>
            <td> {{ x.Name }}</td>
        </tr>
    </table>
</div>
app.js (routing)
----------------------------------
     .when('/getlist', {
            templateUrl: 'views/GetList.html',
            controller: 'MyListCtrl'
        })
index.html
----------------------------------
<script src="scripts/controllers/getList.js"></script>
Comments
Post a Comment