I am trying to call the method ProcessCriteria in AngularJS below but for some reason I am keep getting error message:
VM18010:1 POST http://example.com/api/TalentPool/ProcessCriteria 404
(Not Found)
Below is my Calling code:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: param
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
And my Server side method:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(string Item, string SolrLabel)
{
var itm = Item;
var solr = SolrLabel;
return Ok();
}
Any suggestions please?
ASP.net cannot match your request in its Route Table because you have 2 parameters in your action and the router doesn't understand it.
it expects a data object that your parameters warp to this.
First of all, make a Model like it:
public class Criteria
{
public string Item { get; set; }
public string SolrLabel { get; set; }
}
then change your action:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(Criteria criteria)
{
var itm = criteria.Item;
var solr = criteria.SolrLabel;
return Ok();
}
Update
and update your javaScript part with JSON.stringify:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(param)
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
You can create a class as said by in above answer and you can pass data in http post like this
var obj = {
url: url,
async: true,
method: 'POST',
headers: {
"content-type": "application/json; charset=utf-8",
}
};
if (typeof data != 'undefined' || typeof data != null) {
obj.data = data;
}
$http(obj).then(function(response){
},function(error){
});
I got i working, below is the code for others if they get stuck on it.
var pvarrData = new Array();
pvarrData[0] = JSON.stringify(item.Key);
pvarrData[1] = JSON.stringify(SolrLabel);
pvarrData[2] = JSON.stringify($localStorage.message);
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) {
// failed
console.log('facet post error occured!');
});
Related
I'm Stuck with calling C# web API from angular $http post method as below.
My JSON Object is as below
var requestParams = {
"CostObjects": $scope.costObjForSaveArray,
"CostObjectHierarchies": $scope.costObjHierarchyForSaveArray,
};
API Call with Angular is as below
$http({
method: "POST",
url: API_ROOT + "BusinessDimension/UpdateCostObjects",
data: requestParams,
headers: {
"Content-Type": "application/json"
}
})
Now the API written in .NET is as below.
[HttpPost, ActionName("UpdateCostObjects")]
public HttpResponseMessage UpdateCostObjects([FromBody] JsonData data)
{
var costObjects = JsonConvert.DeserializeObject<List<CostObjectM>>(data.Data);
if (ModelState.IsValid)
{
var updatedCostObjects = Acornpadomainservice.UpdateCostObjects(costObjects).ToList();
return Request.CreateResponse(updatedCostObjects);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
JSON class is as below
public class JsonData
{
public string Data { get; set; }
}
Could anyone correct me what's I'm doing wrong?
Edit the following code
$http({
method: "POST",
url: API_ROOT + "BusinessDimension/UpdateCostObjects",
data: {Data :angular.toJson(requestParams)},
headers: {
"Content-Type": "application/json"
}
})
The angular.toJson(data) will stringfy you object because the Json object is expecting a string type on a Data field to be sent to it
Replace your post method parameter type to object or string in replace of JsonData and check if it's working or not..
Eg.
[HttpPost, ActionName("UpdateCostObjects")]
public HttpResponseMessage UpdateCostObjects([FromBody] object data)
{
var costObjects = JsonConvert.DeserializeObject<List<CostObjectM>>(data.Data);
if (ModelState.IsValid)
{
var updatedCostObjects = Acornpadomainservice.UpdateCostObjects(costObjects).ToList();
return Request.CreateResponse(updatedCostObjects);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
$http({
method: "POST",
url: API_ROOT + "BusinessDimension/UpdateCostObjects",
data: JSON.stringify(requestParams),
contentType: 'application/json; charset=utf-8'
})
In my controller i have the following
[HttpPost]
public string AddEmployee(Employee Emp)
{
if (Emp != null)
{
_context.Employees.Add(Emp);
_context.SaveChanges();
return "Employee Updated";
}
else
{
return "Invalid Employee";
}
}
When i use the following in my angularjs factory no data is passed.
EmployeeService.AddEmp = function (employee) {
console.log(employee);
var response = $http({
method: "post",
url: "/Home/AddEmployee",
data: JSON.stringify(employee),
dataType: "json"
});
return response;
}
but when i use the following data is passed. What am i doing wrong with the above code.
EmployeeService.AddEmp = function (employee) {
console.log(employee);
var response = $http({
method: "post",
url: "/Home/AddEmployee",
params: {
employeeCode: JSON.stringify(employee.employeeCode),
firstName: JSON.stringify(employee.firstName),
lastName: JSON.stringify(employee.lastName),
}
});
return response;
}
I think you'll need to add something like this:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
to WebApiConfig.Register
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.
i am returning a string on updation of a record and want to show the same string on UI(updated successfully)
Here is my code :
#RequestMapping(method = RequestMethod.PUT, value = "/update")
public #ResponseBody String update(#RequestParam("id") int id, #RequestParam("name") String name) {
employeeService.update(id, name);
return "updated successfully";
front end code :
$scope.update = function(Employee) {
$http({
method : 'PUT',
url : '/Employee/update',
params : {
id : Employee.id,
name : Employee.name
}
}).success(function(data, status, headers, config) {
$scope.updatedText = data;
$scope.updatedFlag = true;
}).error(function(data, status, headers, config) {
console.log("data.token " + data.token);
});
};
Here are two interesting screen shots
here status is undefined
again
here status is 200
please let me know what is the reason behind that and yes i can see that there is a change in the hibernate table
Please help
Well i'll leave you an example how i handle calls to the API with $http and promises $q
i use it inside a service, that can be injected on my controllers.
this.update = function (Employee) {
var datosRecu = null;
var deferred = $q.defer();
var token = $cookies.getObject('token');
$http({
url: '/Employee/update',
method: 'PUT',
params: {
id: Employee.id,
name: Employee.name
},
headers: {
'Authorization': 'Bearer ' + token,
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
return deferred.promise;
};
now when i inject it on my controller i can read the promise deferred.promise with all the data of response.
i hope it help you.
i have
$http({
url: 'http://webapi.-----UA_WebApi/GetUserAccount',
method: 'POST',
params: {Username:Username, Password:Password},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
})
and in my service i wrote this method :
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
if anyone could help me understand what i am doing (right and wrong) pls ?
i would also like an example in how to use the angular resource for post.
the PostLogin works
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
.then(function (results) {
if(results.data.TotalRows==1) {}
TotalRows is undefined when debugging. but there is TotalRows in the api
thanks
var actions = {
post: {
method: 'post',
transformResponse: function(data) {
// here is your chance to change received data
return new Model(angular.fromJson(data));
}
}
};
var url = "http://postSomeData/:id/somethingElse/:name";
var parameters = { id : 1, name : "test" }
var data = { name : "test", type : "some type" };
return $resource(url, parameters, actions).post(data).$promise;