I want to post java script object to mvc controller
$(document).ready(function () {
var table = $('#my_table_1').DataTable({
"paging": true,
"ordering": true,
"info": true,
"search": true,
"pageLength": 100
});
var d = '';
var data3 = table.on('search.dt', function () {
//number of filtered rows
// console.log(table.rows({ filter: 'applied' }).nodes().length);
//filtered rows data as arrays
d = table.rows({ filter: 'applied' }).data()
});
console.log(table.rows({ filter: 'applied' }).data());
$('#excel2').click(function (e) {
//var data3 = table.on('search.dt', function () {
// console.log(table.rows({ filter: 'applied' }).data());
// console.log(data3);
//});
console.log(d);
$.ajax({
url: '/Administrator/TestDownload',
type: 'POST',
data: {data:d},
cache: false
}).done(function (response) {
alert(d);
});
});
});
//Controller code:
public JsonResult TestDownload(String[] data)
{
return Json(data,JsonRequestBehavior.AllowGet);
}
I am getting null in controller as a data parameter
Expected: Want to get data object from view to controller as a parameter in controller.
Actual: Data parameter in controller is null
You must check your d variable correct array format.
I tested in my side with var d = ["test",2,3] and in controller it get correct data.
$('#excel2').click(function (e) {
//var data3 = table.on('search.dt', function () {
// console.log(table.rows({ filter: 'applied' }).data());
// console.log(data3);
//});
d = ["test",2,3]
console.log(d);
$.ajax({
url: '/Administrator/TestDownload',
type: 'POST',
data: {data:d},
cache: false
}).done(function (response) {
alert(d);
});
});
});
An example that works:
var test = ["This", "is", "a", "test"];
$.ajax({
type: "POST",
traditional: true,
url: "Administrator/TestDownload",
data: { array: test }
}
});
The controller(in VB.net):
Function TestDownload(array As String()) As ActionResult
//do something
End Function
Why not try stringifying the data and setting the contentType
$.ajax({
url: '/Administrator/TestDownload',
data: JSON.stringify({data:d}), // use JSON stringify
type: 'POST',
contentType: "application/json; charset=utf-8", //add this
cache: false
}).done(function (response) {
alert(d);
});
});
Related
I have created a factory to run an $http GET method. I need to add an input value to the URL pulling in the JSON but I'm having trouble passing it from the controller. I can see that the URL is being created correctly, I am just missing the "query" parameter from the form input field.
Here is my HTML block:
<input type="string" class="form-control" ng-model="getMovie.title">
Here is my factory and controller:
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(){
return $http({
url: url,
method: "GET",
params:{
query: this.title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function(){
getMovie.getMovieInfo().then(function(response){
$scope.results = response;
});
}
}]);
Thanks!
You can send the title as parameter to the factory method.
<input type="string" class="form-control" ng-model="title">
var app = angular.module('app', []);
app.factory("getMovie", ['$http',function($http){
var obj = {};
var url = "https://api.nytimes.com/svc/movies/v2/reviews/search.json";
obj.getMovieInfo = function(title){
return $http({
url: url,
method: "GET",
params:{
query: title, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
this.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
app.controller('moviesCtrl', ["$scope", "getMovie", function($scope, getMovie){
$scope.findMovie = function() {
getMovie.getMovieInfo($scope.title).then(function(response){
$scope.results = response;
});
}
}]);
I recommend you dont use this . If you want use controllerAs syntax , use like this . You can see more in here
https://github.com/johnpapa/angular-styleguide/tree/master/a1#controllers
app.factory("getMovie", ['$http',function($http){
var vm = this
vm.getMovie ={};
And in ajax
return $http({
url: url,
method: "GET",
params:{
query: vm.getMovie, // This is the value I need
api_key: "68094e1974e7984c256beb1653319915:3:33678189",
callback: "JSON_CALLBACK"
},
headers: {
"Content-Type" : "application/json"
}
}).then(function successCallback(response) {
vm.movieReviews = response.data.results;
}, function errorCallback(response) {
console.log("Nothing to see here...");
});
}
return obj;
}]);
I have a global error handler function for $http request.
var errorHandler = function (err) {
// log the error
return {status: err.status, data: {result: -1}}
}
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, errorHandler)
}
How can I pass the variable i to errorHandler?
I know I can do this:
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, function (err) {
// log the error
console.log('i', i) // access i
return {status: err.status, data: {result: -1}}
})
}
But if I want use a global errorHandler, what should I do?
==============
Update:
According to Leandro Zubrezki's answer, we can make it in this way:
var errorHandler = function (err, i) {
// log the error
return {status: err.status, data: {result: -1}}
}
var get = function (url) {
var i = 1 // I have a temp variable here, and want to pass it to errorHandler
return $http({
method: 'GET',
url: ***,
timeout: 5000,
}).then(function (response) {
// do some thing
return response
}, function(error){
errorHandler(error, i)
})
}
This is a stupid question from newbie. :)
Do it like this:
function(error) {
errorHandler(error, i);
}
I am new to Angular and having hard time to understand how to get the value from a resolved promise. I used $q.all([element1.$promise, e2.$promise]). I got the element1 which is a json object. For, element2 which is a scalar containing 2.0. I tried element[1] just like element[0] but it contains no property, so I don't know how to get the value. I tried .val, .data, etc. I know both the web api and angular are getting 2.0.
resolve: {
accountResource: "accountResource",
account: function(accountResource, $stateParams, $q) {
var info = accountResource.get({ accountId: $stateParams.accountId });
var currentBalance = accountResource.getCurrentBalance({ accountId: $stateParams.accountId });
return $q.all([info.$promise, currentBalance.$promise]);
}
vm.account = account[0];
vm.currentBalance = account[1];
resource function
function accountResource($resource) {
var webApiUrl = "https://localhost:44301";
return $resource(webApiUrl + '/api/account/:accountId', {}, {
get: {
method: 'GET'
},
query: {
method: 'GET',
isArray: true,
url: webApiUrl + '/api/account/search/:queryMethod/:queryString'
},
getCurrentBalance: {
method: 'GET',
url: webApiUrl + '/api/account/getcurrentbalance/:accountId'
}
});
}
You can call $q.all likes this (with dictionary instead of array):
return $q.all({info: info.$promise, currentBalance: currentBalance.$promise})
And after that get information in this way:
vm.account = account.info;
vm.currentBalance = account.currentBalance;
Try to rewrite your resource as this:
function accountResource($resource) {
var webApiUrl = "https://localhost:44301";
// Add second parameter {accountId: "#accountId"}
return $resource(webApiUrl + '/api/account/:accountId', {accountId: "#accountId"}, {
get: {
method: 'GET'
},
query: {
method: 'GET',
isArray: true,
url: webApiUrl + '/api/account/search/:queryMethod/:queryString'
},
getCurrentBalance: {
method: 'GET',
url: webApiUrl + '/api/account/getcurrentbalance/:accountId'
}
});
}
Updated
You can add transformResponse property to your getCurrentBalance function in accountResoure. And transform your value from API to json format.
getCurrentBalance: {
method: 'GET',
url: webApiUrl + '/api/account/getcurrentbalance/:accountId',
transformResponse: function (balanceFromApi) {
return { balance: balanceFromApi };
}
}
And finally you can get information, likes this:
vm.account = account.info;
vm.currentBalance = account.balance;
I tested it with $httpBackend service and everything is fine now. Hope this helps.
I have the following base class which handles all request
makeRequest: function(mydata) {
Ext.Ajax.request({
url: './handler.php',
method: 'GET',
scope: this,
params: {
data: mydata
},
callback: this.myResponse,
success: function(xhr, params) {
console.log('Success');
},
failfure: function(xhr, params) {
console.log('Failure');
}
});
}
In my controller I have
.............
requires: [
'Test.libs.Request'
],
............
onItemClick: function() {
var objCallback = Ext.create('Test.libs.Request', {
scope: this
});
objCallback.makeRequest(1);
},
myResponse: function(options, success, response) {
console.log(response);
}
After success executes, how can I get to the controller's myResponse as a callback?
You need to pass along the fn and the scope, something like:
Ext.create('Test.libs.Request', {
callback: this.myResponse
scope: this
});
// You need to get a reference to those passed params inside your request method.
Ext.Ajax.request({
url: './handler.php',
method: 'GET',
scope: passedScope,
params: {
data: mydata
},
callback: passedCallback
});
I have created a resource object:
factory('TextResource',
function($resource) {
return $resource(adminBaseUrl+'/texts/:type', {}, {
create: {method: 'POST', params: {type:'create'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
update: {method: 'POST', params: {type:'update'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
query: {method: 'GET', params: {type: 'list'}},
remove: {method: 'POST', params: {type: 'remove'}, headers: {'Content-Type':'application/x-www-form-urlencoded'}},
getText: {method: 'GET', params: {type: 'get', id:'#id'}}
});
}
)
And my controller is:
controller('EditText', ['$scope', '$location', '$routeParams', 'TextResource', 'HttpStatusMessage',
function($scope, $location, $routeParams, TextResource, HttpStatusMessage) {
$scope.alerts = [];
$scope.languages = [];
TextResource.getText(
{id: $routeParams.id},
function(data) {
$scope.languages = data.result;
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
}
$scope.submit = function() {
TextResource.update(
$scope.languages,
function(data) {
if( data.type == 'success' ) {
$location.path('texts');
} else {
$scope.alerts.push({type:data.type, msg:data.message});
}
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
}
$scope.cancel = function() {
$location.path('texts');
}
}
])
The response i am getting from TextResource.getText request is:
{"result":[{"id":"3","value":"This is my first text<br>","key":"my_first_text","language_id":"1","name":"English"},{"id":"3","value":"Ceci est mon premier texte","key":"my_first_text","language_id":"3","name":"French"}],"num_rows":2}
Now when i click on submit it displays the error:
Error: a.push is not a function
The response object contains 2 keys result and num_rows result is an array. The reason i am not using isArray parameter in resource object is in case if any error occured in server like session time out, access not allowed etc. the server returned a object contains error msg.
Problem is solved by modifying the update function like:
$scope.submit = function() {
TextResource.update(
{'language':$scope.languages},
function(data) {
if( data.type == 'success' ) {
$location.path('texts');
} else {
$scope.alerts.push({type:data.type, msg:data.message});
}
},
function(error) {
var httpError = new HttpStatusMessage(error.status);
$scope.alerts.push({type:'error', msg:httpError.msg});
});
}
I was directly posting an array in update which throws the error. So encapsulating in another key solved the problem.