WEB API POST data from UI Angular JS and Store in DataBase
Step1 : UI - Html File
<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>
Index.html file -Add
<script src="scripts/controllers/getList.js"></script>
app.js - Add
.when('/getlist', {
templateUrl: 'views/GetList.html',
controller: 'MyListCtrl'
})
Controller File - getList.js
'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;
});
$scope.add = function () {
var data ={
"email": $scope.id
}
var config={
header: 'Content-Type : application/json;charset=utf-8;'
}
console.log("I am here");
console.log(data);
$http.post('http://localhost:24871/api/Post/AddEmail',data,config).success(function(data,status,header,config)
{
$scope.PostDataResponse = data;
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
});
DataBase
Create a procedure to accept parameter and insert into DataBase Table
CREATE TABLE [dbo].[MyTable] (
[Id] INT NOT NULL,
[MailId] NVARCHAR (80) NOT NULL,
[SubscriberDate] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Create procedure InsertData
(
@email varchar(80)
)
as
begin
declare
@id int
select @id=max(Id) from MyTable
set @id=@id+1
insert into Mytable values(@id,@email,getdate())
end
select * from MyTable
Developing the WEB API:
Create a MVC 4 API Project
1) Add a class under the Service which will be a repository and will communicate with the database
and store the value to it
using ContactManager.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace ContactManager.Service
{
public class InsertRepository
{
public string AddEmail(Email em)
{
string str = ConfigurationManager.ConnectionStrings["EmailConn"].ToString();
SqlConnection conn = new SqlConnection(str);
SqlCommand cmd = new SqlCommand("InsertData", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@email", em.email);
conn.Open();
int i = cmd.ExecuteNonQuery();
if (i >= 1)
{
return "Email Inserted :Success";
}
else
{
return "Email Inserted : Failure";
}
}
}
}
3) Add Controller class
using ContactManager.Models;
using ContactManager.Service;
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 PostController : ApiController
{
static InsertRepository repo = new InsertRepository();
public string AddEmail(Email em)
{
var response = repo.AddEmail(em);
return response;
}
}
}
<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>
Index.html file -Add
<script src="scripts/controllers/getList.js"></script>
app.js - Add
.when('/getlist', {
templateUrl: 'views/GetList.html',
controller: 'MyListCtrl'
})
Controller File - getList.js
'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;
});
$scope.add = function () {
var data ={
"email": $scope.id
}
var config={
header: 'Content-Type : application/json;charset=utf-8;'
}
console.log("I am here");
console.log(data);
$http.post('http://localhost:24871/api/Post/AddEmail',data,config).success(function(data,status,header,config)
{
$scope.PostDataResponse = data;
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
});
DataBase
Create a procedure to accept parameter and insert into DataBase Table
CREATE TABLE [dbo].[MyTable] (
[Id] INT NOT NULL,
[MailId] NVARCHAR (80) NOT NULL,
[SubscriberDate] DATETIME NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
Create procedure InsertData
(
@email varchar(80)
)
as
begin
declare
@id int
select @id=max(Id) from MyTable
set @id=@id+1
insert into Mytable values(@id,@email,getdate())
end
Developing the WEB API:
Create a MVC 4 API Project
1) Add a class under the Service which will be a repository and will communicate with the database
and store the value to it
using ContactManager.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace ContactManager.Service
{
public class InsertRepository
{
public string AddEmail(Email em)
{
string str = ConfigurationManager.ConnectionStrings["EmailConn"].ToString();
SqlConnection conn = new SqlConnection(str);
SqlCommand cmd = new SqlCommand("InsertData", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@email", em.email);
conn.Open();
int i = cmd.ExecuteNonQuery();
if (i >= 1)
{
return "Email Inserted :Success";
}
else
{
return "Email Inserted : Failure";
}
}
}
}
3) Add Controller class
using ContactManager.Models;
using ContactManager.Service;
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 PostController : ApiController
{
static InsertRepository repo = new InsertRepository();
public string AddEmail(Email em)
{
var response = repo.AddEmail(em);
return response;
}
}
}
Step 4:Add Model Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ContactManager.Models
{
public class Email
{
public string email { get; set; }
}
}
Step 5: Add the below connection String in the web .config file
<connectionStrings>
<add name="EmailConn" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\StateDesignPattern\REST_Example1\ContactManager\ContactManager\App_Data\ContactManager.mdf;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Step 6 : Configure the WebApiConfig.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
namespace ContactManager
{
public static class WebApiConfig
{
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"));
}
}
}
Step 7: Configure the RouteConfig .cs files
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace ContactManager
{
public class RouteConfig
{
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 8: Configure the 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>
Comments
Post a Comment