I am trying to Post an object from AngularJS to a MVC 5 WebApi Controller, but the value is always null
I can see in Chrome dev tools that the data can be found on the request.
Angular Controller:
$scope.join = function () {
if (!$scope.joinForm.$valid) return;
// Writing it to the server
var payload = $scope.user;
var res = $http.post('/api/some', JSON.stringify( { Data: { payload } }), { header: { 'Content-Type': 'application/json' } });
res.success(function (data, status, headers, config) {
$scope.message = data;
});
res.error(function (data, status, headers, config) {
alert("failure message: " + JSON.stringify({ data: data }));
});
}
MVC 5 API Controller:
public class SomeController : ApiController
{
// POST api/values
public void Post([FromBody]string value)
{
Trace.Write(value);
}
}
If I wrap my object in {Data: {payload}}
{"Data":{"payload":{"symbol":"xxx","amount":12000,"startdate":"2014-05-23T14:26:54.106Z","enddate":"2015-05-23T14:26:54.106Z","interval":"7 minutes"}}}
if I dont wrap it I get:
{"symbol":"xxx","amount":12000,"startdate":"2014-05-23T14:26:54.106Z","enddate":"2015-05-23T14:26:54.106Z","interval":"7 minutes"}
(Visual Studio 2015 is configured to use IISExpress)
Any ideas?
The reason
value
was null is because the framework's model binder was unable to match the parameter to the data that was sent in the body of the post.Create a class to store your payload
update controller
Angular controller