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!!
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;
})
}
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;
})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.