AngularJS nullable parameter missing in ASP.NET Web Service method - javascript

I am calling an ASP.NET Web Service Method with a nullable optional paramter from an AngularJS controller. It works fine if I provide the parameter value but don't work if the parameter value is not provided!! and shows he following error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and In details:
System.InvalidOperationException: Missing parameter: name.
at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
at System.Web.Services.Protocols.UrlParameterReader.Read(HttpRequest request)
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
Here is Web service Method:
[WebMethod]
public void GetAllStudents(string name)
{
IQueryable<Student> listStudents = dbContext.Students;
if (!String.IsNullOrEmpty(name))
{
listStudents = listStudents.Where(x => x.name.Contains(name));
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(listStudents.ToList()));
}
Here is My Route Config:
$routeProvider.when("/students/:name?",
{
templateUrl: "Templates/Students.html",
controller: "studentsController",
})
Here is My Controller:
.controller("studentsController", function ($scope, $http, $route, $location, $routeParams) {
$scope.message = "Student Page";
$scope.studentSearch = function () {
if ($scope.name) {
$location.url("/students/" + $scope.name);
}
else {
$location.url("/students");
}
}
if ($routeParams.name) {
$http({
method: "GET",
url: "StudentService.asmx/GetAllStudents",
params: { name: $routeParams.name }
})
.then(function (response) {
$scope.students = response.data;
})
}
else {
$http.get("StudentService.asmx/GetAllStudents")
.then(function (response) {
$scope.students = response.data;
})
}
})
*Any Help please!!

It works but looks a bit of ugly with two if statement successively
if ($routeParams.name) {
$http({
method: "GET",
url: "StudentService.asmx/GetAllStudents",
params: { name: $routeParams.name }
})
.then(function (response) {
$scope.students = response.data;
})
}
if ($routeParams.name == undefined) {
$http({
method: "GET",
url: "StudentService.asmx/GetAllStudents",
params: { name: ""}
})
.then(function (response) {
$scope.students = response.data;
})
}

instead of write if else statement just check that param before sending and assign null if there is no value in that or if it is undefined
$routeParams.name = (!angular.isUndefined($routeParams.name) && $routeParams.name != "")?$routeParams.name:"";
$http({
method: "GET",
url: "StudentService.asmx/GetAllStudents",
params: { name: $routeParams.name }
})
.then(function (response) {
$scope.students = response.data;
})
}

Related

How to call php file via factory/service method using Angular.js

I need to call php file using service/Factory method using Angular.js. Here instead of calling $http repeatedly in each file to call diferent php file for different purpose, I need to make it common. I am explaining one example below.
logincontroller.js:
var loginAdmin=angular.module('Takeme');
loginAdmin.controller('loginController',function($scope,$http,$location,$window,inputField){
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
},function errorCallback(response) {
});
}
I have one common route.js file which is common for all controller and given below.
route.js:
var Admin=angular.module('Takeme',['ui.router', '720kb.datepicker','ngMessages','ngCapsLock','ui.bootstrap','ngFileUpload','angularUtils.directives.dirPagination']);
Admin.run(function($rootScope, $state) {
$rootScope.$state = $state;
});
Admin.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('/',{
url: '/',
templateUrl: 'view/login.html',
controller: 'loginController'
})
})
Admin.factory('inputField',function($timeout,$window){
return{
borderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.focus();
element.style.borderColor = "red";
}
});
},
clearBorderColor:function(id){
$timeout(function() {
var element = $window.document.getElementById(id);
if(element){
element.style.borderColor = "#cccccc";
}
});
}
};
});
Here I need to that $http service to call the php file common for which in every controller I will call that $http repeatedly. I need to pass only the parameters for $http service and return the response.
create a factory/service
angular.module('myApp').factory('DataService', DataService);
DataService.$inject = ['$http', '$q'];
function DataService($http, $q) {
return {
getData: getData,
}
function getData(userData) {
var deferred = $q.defer();
$http({
method: 'POST',
url: "php/Login/verify.php",
data: userData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
deferred.resolve(response.data);
},
function(error) {
deferred.reject(error.data);
});
return deferred.promise;
};
}
then use this factory whenever you need in a controller
angular.module('myApp')
.controller('MyController', ['$scope', 'DataService',
function($scope, DataService ) {
$scope.getMyData = function() {
var data = {};
DataService.getData(data)
.then(function(response) {
}, function(error) {
});
};
}
]);

How to pass form parameters to Rest using angularjs services?

I try to pass my form parameters to java rest backend but i cant.
controller
$scope.addNewThing = function () {
Myservice.addNew($scope.name);
};
service
addNew: function (name) {
var Foo = $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {}}
});
var results = Foo.save({name: name}, function(data) {
results = data;
});
return results;
}
//also tried this version of code
addNew: function(name) {
return $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {name: 'test'}}
});
}
rest backend function
#POST
#Produces("application/json")
#Path("/addNew")
public Response addNew(#FormParam("name") String name) {
try {
//when i check name here it is always null
...
}
}
I can't pass the html form parameter to java rest backend via angular. Also tried to change #FormParam to #QueryParam but it didn't work.
Did you set the default content-type on $http POST requests?
app.config(function($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
});
I don'n know how to receive params value in java but I can show how to pass params from angular service. when you will want to pass params then you should use :paramsName in your URL path.
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {name: '#name'}, {
'post': {method: 'GET'}
});
return addNewItem.post({name: name});
}
or if you don't use /:name in your url you should pass in your header
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {}, {
'post': {method: 'GET', headers: { 'name': name }}
});
return addNewItem.post({name: name});
}
NB: your Content-Type should be application/json
You can try this:
CONTROLLER
$scope.addNewThing = function () {
yourService.addNew($scope.name);
};
SERVICE
angular.module('MyApp')
.service('yourService',['$http', function ($http) {
this.addNew = function (data) {
$http({
url: 'YourURL',
method: 'POST',
data: data, // your $scope.name
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function (response) {
console.log('good');
})
.error(function (response) {
console.log('error');
});
};
}]);
JAVA REST API
#POST
#Path("/addNew")
#Consumes("*/*")
public Response addNew(String name) {
// use here your String name
}
Using jQuery params solved my problem
Here is the correct way:
Myservice.addNew().save($.param({
name:$scope.name
}),function(data){
console.log(data);
},function(err){
console.log(err);
});
I can pass the parameters like this with $resource service.

$http post via an angularjs service

I use the code below. The content of dataService is all the $http possible in my application. In the controller, I consume this function. The function call a Web Api service, this one is called and return the right response. In the function customerToggleSuccess the data is undefined. I don't understand why.
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
.then(customerToggleData)
.catch(customerToggleError)
}
function customerToggleData(response) {
return response.data;
}
function customerToggleError(response) {
}
}
}());
(function () {
angular.module('myApp')
.controller('customerController', ['$scope', 'dataService', '$http', '$log', CustomerController]);
function CustomerController($scope, dataService, $http, , $log) {
var vm = this;
vm.activeToggle = function (customerId, index) {
dataService.customerToggleActive(customerId, index)
.then(customerToggleSuccess)
.catch(customerToggleCatch)
.finally(customerToggleComplete);
function customerToggleSuccess(data) {
$log.info(data);
}
function customerToggleCatch(errorMsg) {
}
function customerToggleComplete() {
}
}
}
}());
Like this ,
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http']);
function dataService($q, $http,) {
return {
customerToggleActive: customerToggleActive
};
function customerToggleActive(customerId, index) {
var customer = {
"id": customerId,
"index": index
};
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
}
}
}());
Simply return the $http promise,
return $http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
you can access it by,
dataService.customerToggleActive(customerId, index)
.then(function (response) {
// do your stuff
})
or, you can do,
function dataService($q, $http,) {
var defer = $q.defer();
....
....
$http({
method: 'POST',
url: 'api/customer/validtoggle/',
headers: {
},
transformResponse: function (data, headers) {
},
data: customer
})
function customerToggleData(response) {
defer.resolve (response.data);
}
function customerToggleError(response) {
defer.reject(response);
}
return defer.promise;
}

Use parameters in angular factory for custom header

I'm trying to find a way to pass a parameter so I can use it in my 'endpoint' variable, as you can see in my code I have the url and in the end of it I have "/clientes", but, in my API I also have "products" and "travels", so I'm looking for a solution to use a variable so I can change the end of the url, otherwise I'll have to create another factories just to get my "products" and my "travels".
angular.module('starter.services', [])
.factory('ServiceClientes', ['$http', function ($http) {
var endpoint = 'http://api.rep.com/api/clientes';
var token = '99KI9Gj68CgCf70deM22Ka64chef2J2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8';
var credencial = 'rm#w.com:cd8cdx5ef753a06ee79fc75dc7cfe66c';
var origem = 'mobile';
var config = {
url: endpoint,
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function () {
return $http(config);
}
};
}]);
controller:
.controller('PlaylistsCtrl', function ($scope, ServiceClientes) {
ServiceClientes.getAll().success(function (data) {
$scope.playlists = data.dados;
}).error(function (error) {
console.log(error);
});
})
Then make your function injectable with a parameter:
var endpoint = 'http://api.rep.com/api/';
var config = {
dataType: 'json',
method: 'GET',
data: '',
headers: {
'X-API-TOKEN': token,
'X-API-CREDENCIAL': credencial,
'X-API-ORIGEM': origem,
"Content-Type": "application/json"
}
};
return {
getAll: function (url) {
config.url = endpoint + url;
return $http(config);
}
};
controller:
ServiceClientes.getAll("clientes").success(function (data) {

AngularJS passing data to $http.get request

I have a function which does a http POST request. The code is specified below. This works fine.
$http({
url: user.update_path,
method: "POST",
data: {user_id: user.id, draft: true}
});
I have another function for http GET and I want to send data to that request. But I don't have that option in get.
$http({
url: user.details_path,
method: "GET",
data: {user_id: user.id}
});
The syntax for http.get is
get(url, config)
An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.
angular.http provides an option for it called params.
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params param)
You can pass params directly to $http.get() The following works fine
$http.get(user.details_path, {
params: { user_id: user.id }
});
Starting from AngularJS v1.4.8, you can use
get(url, config) as follows:
var data = {
user_id:user.id
};
var config = {
params: data,
headers : {'Accept' : 'application/json'}
};
$http.get(user.details_path, config).then(function(response) {
// process response here..
}, function(response) {
});
Solution for those who are interested in sending params and headers in GET request
$http.get('https://www.your-website.com/api/users.json', {
params: {page: 1, limit: 100, sort: 'name', direction: 'desc'},
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
Complete service example will look like this
var mainApp = angular.module("mainApp", []);
mainApp.service('UserService', function($http, $q){
this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {
var dfrd = $q.defer();
$http.get('https://www.your-website.com/api/users.json',
{
params:{page: page, limit: limit, sort: sort, direction: direction},
headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
if ( response.data.success == true ) {
} else {
}
}, function(x) {
dfrd.reject(true);
});
return dfrd.promise;
}
});
You can even simply add the parameters to the end of the url:
$http.get('path/to/script.php?param=hello').success(function(data) {
alert(data);
});
Paired with script.php:
<? var_dump($_GET); ?>
Resulting in the following javascript alert:
array(1) {
["param"]=>
string(4) "hello"
}
Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:
CONTROLLER:
public class AngularController : Controller
{
public JsonResult GetFullName(string name, string surname)
{
System.Diagnostics.Debugger.Break();
return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
}
}
VIEW:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.GetFullName = function (employee) {
//The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue
$http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
success(function (data, status, headers, config) {
alert('Your full name is - ' + data.fullName);
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="text" ng-model="name" />
<input type="text" ng-model="surname" />
<input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>
For sending get request with parameter i use
$http.get('urlPartOne\\'+parameter+'\\urlPartTwo')
By this you can use your own url string

Categories