How to POST Json Object to Webapi method using AngularJs and WebAPI?

Rajnilari2015
Posted by Rajnilari2015 under Android category on | Points: 40 | Views : 288
index.html
-------------

<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js">
</script>
<script>
var app = angular.module("testApp", []);
app.controller("testCtrl", function ($scope, $http) {

$scope.sendJSonData = function () {

var employee = {
EmployeeName: "TestEmployeeName",
Age: "32"
};

$http.post('http://localhost:22900/Employee/EmpRecords', employee)
.success(function (data, status, headers, config) {
$scope.serverResponse = data;
})
.error(function (data, status, header, config) {
alert(status);
});
};

});
</script>

</head>

<body ng-app="testApp">
<div ng-controller="testCtrl">
<button ng-click="sendJSonData()">Submit</button>
<p>{{ serverResponse }}</p>
</div>
</body>
</html>


WebAPI
-------------

using System;
using System.Collections.Generic;
using System.Web.Http;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
[RoutePrefix("Employee")]
public class EmployeeController : ApiController
{
[Route("EmpRecords")]
[HttpPost]
public string InsertEmployees([FromBody]Employee emp)
{
var record = emp;
return "server response" + " EmployeeName : " + record.EmployeeName + " Age: " + record.Age;
}
}

public class Employee
{
public string EmployeeName { get; set; }
public int Age { get; set; }
}
}

Comments or Responses

Login to post response