POSTing value from Angular to MVC controller results in null value - angularjs

I am attempting to pass a value from angular to my MVC Core controller to use in a repository function as simple string. However, I've noticed that it's passing a null value to the MVC controller. I don't want to create an MVC model just to use the POSTed JSON as a string.
Function excerpt from MVC controller
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromBody] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
$Http Angular function
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then(function (response) {
// success
console.log(response);
vm.Specials.push(response.data);
angular.copy(response.data, vm.Specials);
console.log(vm.Specials);
// clear the form
vm.newSpecials = {};
}, function (response) {
// failure
console.log("Error !" + response.data);
vm.errorMessage = "Failed to save subscription";
})
.finally(function () {
vm.isBusy = false;
});

In mvc controller you are passing action parameter as string.
Please check you "siteID" Type in your JS.
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

From your example it looks like you should probably be performing a GET rather than a POST, however you can adapt your methods as follows to get up and running:
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromUri] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
And your angular function:
$http.post('/api/organisations/test?siteID=' + siteID)
.then(function (response) {
...
})
.finally(function () {
...
});

Try to pass object in $Http Angular function.
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: {siteID: siteID},
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then....
For more just check $http service documentation here.

Related

How to fix the issue-No action was found on the controller that matches the name on sending JSON object to ASP.NET WebAPI from AngularJS

I need to pass data entered in AngularJS front end to webAPI and retrieve another set of data to populate on a grid. I am trying to pass data as JSON object to webAPI method. In WebAPI method, the parameter I am passing for the JSON object as a Class object.
I am not able to enter to the particular webAPI method when I am using [HTTPPost] and getting error as-No action was found on the controller that matches the request.
But I am able to enter to other webAPI methods having [HTTPGet].
Can someone please advise how to fix the issue.Thanks !
WebAPI
using System.Web.Http;
using AttributeRouting.Web.Http;
namespace webAPITestProject.Controllers
{
[Route("api/Values")]
public class ValuesController : ApiController
{
retrieveEmployeeData empData = new retrieveEmployeeData();
retrieveProductDetails prodDetls = new retrieveProductDetails();
[Route("PostEmployeeData")]
[HttpPost]
public DataTable PostEmployeeData([FromBody] Employer empDetails)
{
DataTable dataTable = new DataTable { TableName = "MyTableName" };
dataTable = empData.getEmployeeData(empDetails);
return dataTable;
}
}
}
AngularJS-Controller
angular.module('Test.Employer')
.controller('EmployerController', ['$scope','headerValue', '$http',
function ($scope, headerValue, $http) {
var ipEmployerDetls = {
EmployerName: "cherokee",
Company: "ABC"
};
$http({
url: 'http://localhost:53583/api/Values/PostEmployeeData?empDetails='+'"'+JSON.stringify(ipEmployerDetls)+'"',
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
})();
Employer class
public class Employer
{
public string Company{get;set;}
public string EmployerName{get;set;}
}
you are POSTing data to an endpoint, you don't need to add anything in the URL.
$http({
url: 'http://localhost:53583/api/Values/PostEmployeeData',
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
I have cleaned up your call, the data you provide is sent in the body of the message and your controller expects it there as indicated by the [FromBody] tag

Angular $http called from service, 'then' is undefined

I have seen this question many times but I can't figure out why one of my controller functions (controller 1) works fine and one (controller 2) doesn't.
Controller 1:
angular.module('app').controller('MyCtrl1',function($scope,MyFactory)) {
//This function works great
MyFactory.deleteItem(item.id).then(function(response) {
//woot woot I am here and I am fine
});
}); //end controller 1
Controller 2:
angular.module('app').controller('MyCtrl2',function($scope,MyFactory)) {
//Function #2 that doesn't work ... 'then' is undefined
MyFactory.createItem(item).then(function(response) {
//booo hooo I never get here and I am definitely not fine
});
}); //end controller 2
The factory:
.factory("MyFactory", function($http) {
var service = [];
service.deleteItem = function(itemId) {
return $http({
method: "delete",
url: "http://www.example.com",
params: //valid params go here
}).then(function(response) {
console.log("DELETING!!!!");
return response.data;
});
}
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
return service;
}); //end factory
The error thrown when executing 'createItem' is 'Cannot read property 'then' of undefined' What am I missing ?
You are missing the return in the createItem statement:
service.createItem = function(post) {
return $http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).then(function(response){
console.log(response.data); //we are fine here. there is a valid response
return response.data;
});
}
Without it, there is no return value (which is undefined) on which you can't chain the .then.
If you are not returning $http the use like this :
$http({
url: '?create',
method: 'post',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: payload //an object
}).$promise.then(function(response){
console.log(response.data);
return response.data;
});

Angular $http get method does not send correct data to server

I am new at angular. I use angular.js and webapi. I have a request like below.
[HttpGet]
public RecordDTO[] GetMyFiles(UserClass usr,int uId,int fId)
{
}
my webapi call is like this. UserClass parameter is a class that has two string field(name,password). My angular code is like below.
$scope.GetMyFiles= function () {
var user = { Name:'xx',Password:'xx' };
var data = {usr:user, uId: 11, fId: 56};
$http({
url:"../api/Home/GetMyFiles",
method: 'GET',
//headers: { 'Content-Type': 'application/json' },
params: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});
};
My problem is UserClass is null. It takes uId and fId parameters, but first parameter comes null.
How can I correct this?
Thanks in advance.
As the default content-type for $http is JSON, check what your service is attending. If its JSON, you should stringify your data to pass them to your webapi :
params: JSON.stringify(data)
if you need to SEND data to the server, you should make a $http.post call. I think the problem because you are not specifiying the content-type of the header.
please try this:
$http.post('/api/Home/GetMyFiles', data , {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;' }
}
).success(function(data) })
.error(function(err){});
Tell me if it works, and if you need any help let me know. Happy Coding. ;)
Change $http method from GET to POST. Also change params: data to data: data. I tried this code in my local PC and it works correctly.
Controller:
[HttpPost]
public RecordDTO[] GetMyFiles(UserClass usr, int uId, int fId )
{
}
JavaScript:
$http({
url: url,
method: 'POST',
data: data
})
.success(function (data) {
alert("OK");
})
.error(function (data) {
alert("error");
});

how to send x-www-form-urlencoded data using ngResource module with angular?

everything lives in the title.
when producing a resource in angular :
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id');
}]);
and using in a controller :
MyResource.save({att: att, att2: att2});
the Service sends the data in a json artifact ahead to the server.
I need to send the data in a x-www-form-urlencoded shape.
Where ought I modify my code to resolve that ?
Should pass the headers parameters
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}]);
then serialize your data before sending them with $httpParamSerializer
myModule.controller('appController', function ($httpParamSerializer) {
MyResource.save($httpParamSerializer({att: att, att2: att2}));
}
Complete answer (since angular 1.4). You need to include de dependency $httpParamSerializer
var res = $resource(serverUrl + 'Token', { }, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
res.save({ }, $httpParamSerializer({ param1: 'sdsd', param2: 'sdsd' }), function (response) {
}, function (error) {
});
I finally found myself:
When defining a resource and the associated instruction, the "headers" parameter comes in hand.
myModule.factory('MyResource', ['$resource', function ($resource) {
return $resource('api/MyResource/:id', {}, {
save: { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
});
}]);

Sending POST request with form-urlencoded parameters in AngularJS using ngResource

I am trying to do a POST request with ngResources in AngularJS, I want to send my parameters in url and I have changed headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, in $save method in ngResources. The request goes out with the correct content type, but the data goes as a JSON. Is there any standard way to overcome this problem?
The factory
.factory('Token', ['$resource', function ($resource) {
return $resource('http://myProject/token/ ', { }, {
save: {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
});
}])
The calling function
.service('tokenService', ['$http', 'Token',
function ($http, Token) {
this.getToken = function () {
var t = new Token()
t.name = 'myName';
t.password = '78457'
return t.$save();
};
}])

Resources