Hi I am developing one application using web api2 and angularjs. Finding hard time to send data to web api methods. I am having problem to send data as objects n PUT and POST methods. In delete and getbyid methods i am able to send single parameter but i am not able to send data as object. I am receiving null as below.
I am calling as below using angularjs.
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: sub,
url: '/NCT_Users/',
// contentType: "application/json"
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
}
If i comment header and uncomment contentType in above code I am getting totally null object as below.
May i know why i am not able to bind object to model? Any help would be appreciated. Thank you.
var person = {firstName:"John", lastName:"Doe", age:46};
$http.post('url', person)
.success(function (response){
alert(response);
});
accesstoken is defined variable.you can define your variables to pass it to server
var person = {
firstName:"John",
lastName:"Doe",
age:46
};
$http.post('url', person)
.success(function (response) {
alert(response);
});
try this way.
var sub = {
User_CreatedDate: "",
UserEmailId: "",
User_Id: "",
User_MobileNum: "",
User_Name: "",
User_Password: "",
User_Role: "",
User_Status: "",
User_UpdateDate: ""
};
$http.post('/NCT_Users/', sub).success(function (response) { alert(response); });
the fields are filled by you
It happens like this because you are sending an JS Object via an 'application/x-www-form-urlencoded' header. You have to send the data as parameters, try this updated function:
this.saveSubscriber = function (sub) {
return $http({
method: 'POST',
data: $.param(sub),
url: '/NCT_Users/',
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}
Related
I am using Angular 1.4.4 and Django 1.8. When i post data from Angular to Django view it comes in the form of whole data as key in the QueryDict.
So in view in debug mode when i evaluate request.POST it returns this
<QueryDict: {u'{"messagetitle":"","value":"","valueam":"","wrong_response":"","stop":"","messagekind":"1","undefined":"","messagetype":"3","state":"","language_id":1}': [u'']}>
Notice posted data is inside u'' as key and its value is [u'']
Angular dataservice code is this
function createDraft(data) {
return $http({
url: view_url + 'create_draft/',
method: 'POST',
data: data,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
}
Controller code
app.controller('message',function($scope, $ngBootbox, dataservice, $http){
$scope.formData = {
"messagetitle":"", "value":"", "valueam":"",
"wrong_response": "", "stop": "", "messagekind": "1",
"undefined_response": "", "messagetype":"3",
"state": "", "language_id":1
};
saveDraft = function(){
dataservice.createDraft($scope.formData).then(
function(res) {
$ngBootbox.alert("<div class='alert-success alert_box'>Draft Saved</div>")
},
function(res) {
var error_message = res['statusText'].trim();
if (error_message === '')
error_message = 'Error Occurred';
$ngBootbox.alert("<div class='alert-warning alert_box'>" + error_message + "</div>")
})
}
saveDraft function is called from angular template(which is html form) on button click.
Let me know what i am doing wrong here. I have tried some answers on stackoverflow but could not find any question/answer which addresses my specific problem.
PS:
I know i can do json.loads(request.body) but i need to post data in django's request.POST
Use $.param(data) instead of data in your service
I have to send json object as a value with a key.
My Code:
var req = {
method: 'POST',
url: clientAdd_url,
headers: {
'Content-Type': 'application/json'
},
data: {Contact: $scope.clientinfo}
}
Contact is a key and $scope.clientinfo is a json object. But it's not working.
I checked in Postman, the format is like:
{
Contact: {
"BillingDetails": {
"CompanyName": "Shangrila Handicraft Shop",
"Address": "Kamaladi"
},
"ContactDetails": {
"ContactName": "Shyam Shrestha",
"ContactEmail": "shyam#gmail.com",
"ContactPhone": 9808909090
},
"ShippingDetails": {
"ShippingName": "Shangrila Handicraft Shop",
"ShippingAddress": "Kamaladi"
},
"Notes": "Test from Postman"
}
I would be grateful for your help.
place all those in to a obj as below...
$scope.datelvl = { "date": $scope.date, "tanklevel": $scope.Tank_level };
later call to backend controller for method like below:
$.ajax({
type: 'POST',
url: apiUrl + 'yourcontrollername/methodname',
data: datelvl,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function (data)
{
}
$scope.clientinfo looks like its a JSON object. By what I understand from your question, looks like you want to send $scope.clientinfo as a string. For that you could convert the JSON object to a string using the JSON.stringify
data: {"Contact": JSON.stringify($scope.clientinfo)}
see: http://www.json.org/js.html
Try this.It might useful.
angular.module('appCtrl1', []).controller('AppCtrl',function($scope,$http){
var tempData = {"Contact": $scope.clientinfo};
$http({
method: 'POST',
url: serverURL,
headers: { "Content-Type": "application/json" },
data: tempData,
}).success(function(data, status, headers) {
console.log(data);
}).error(function(data, status, headers) {
console.log(data);
});
}
Thank you everyone. I was told to send json data with a key as I have stated the original format though it has been little edited. So I was having a hard time. I have used the normal json post of angular in my projects. But since it was not the json, I could not send data through any process. I think many of you didn't get my question. But anyway I am so much thankful for your concern. This problem is solved. They made changes in their end.
I need to do send a json array to a restful api from my angularjs application. I am using ngresources to do this.
Since now, I have been abled to post and put single object with no problem, but now I need to send an array of objects and I can't.
I tried to do the call from a external rest application and it works fine but it's impossible from my angular application. I have trie to parse the objet with JSON.stringify but stills not working. I set the header 'Content-Type': 'application/json', as well on the $resources.
This is how I do the negresource:
.factory('AddSignosClinicos', function ($resource) {
return $resource(dondeapuntar + "/Rest/Pacientedatossignosclinicos.svc/pACIENTEDATOSSIGNOSCLINICOSList/Add", {}, {
create: { method: "POST", headers: { 'Content-Type': 'application/json', params: {} } }
});
})
And this is how I call the function:
var objeto = JSON.stringify(SignosClinicosGuardar);
var signosClinicosService = new AddSignosClinicos(objeto);
signosClinicosService.$create().then(function () {});
I made a console.log of objeto, and is a proper json array.
Any idea?
Thank you very much
EDIT
I have tried $http component for the post request, and it worked! I donĀ“t understand why is not working with ngResources, this is my code for $http:
$http({
url: 'http://localhost:1046/Rest/Pacientedatossignosclinicos.svc/pACIENTEDATOSSIGNOSCLINICOSList/Add',
method: "POST",
data: SignosClinicosGuardar,
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
});
To post an array of objects you'll need to add the option isArray: true to your $resource:
.factory('AddSignosClinicos', function ($resource) {
return $resource(
"url-string-here",
{},
{
create: {
method: "POST",
isArray: true
}
}
);
})
Calling the new create function would look something like this:
//some list of your object instances
var array_of_objects = ...
var saved_objects = AddSignosClinicos.create(
array_of_objects
);
saved_objects.$promise.then(function() {
...
});
Note, the create vs $create, there's no $.
See the Angular documentation on $resource
Angular Code:
getAuthorizationStatus: function () {
var deferred = $q.defer();
$http({
method: "POST",
url: url,
data: {
username: $scope.username,
password: $scope.password
},
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
My Server side code:
[HttpPost]
public int ValidateUser([FromBody]Credentials credentials)
{
try
{
string username = credentials.username;
string password = credentials.password;
//Do stuff
}
catch (Exception ex)
{
throw ex;
return -1;
}
return -1; // not valid user
}
The problem I am having is I am able to hit the Api Method but the data inside is always null. I have tried several combinations like this:
data: JSON.stringify({
"username" : "username",
"password":"mypassword"
}),
No dice.
What am I doing in wrong ?
Enclose your data in $.param()
Example :
data: $.param({ username: $scope.username,password: $scope.password })
I would instead trying to change the default and appropriate behavior of $http's POST, instead let the server read the data from the right place. Taken from MVC controller : get JSON object from HTTP body?:
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
It turns out that MVC doesn't really bind the POST body to any
particular class. Nor can you just fetch the POST body as a param of
the ActionResult (suggested in another answer). Fair enough. You need
to fetch it from the request stream yourself and process it.
Using [FromBody] beside the action input param is enough to get the data from request. Your problem is that you override the content-type in your Angular code through headers:
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
}
It must be 'application/json' in order to send json data. Just remove that headers and it should work normally.
I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.