In the following sample of code I send a "request" and I am trying to get a response but that returns "undefined" value.
This is my code so far
$scope.SameNameFunction = function() {
var payload = { itemname: $scope.EventDetails.Name};
portalRepository.namecall(payload).then(function (payload) {
console.log(payload.valuesreturned);
alert("Detected: " + payload.valuesreturned + " events having the same name");
});
};
Code from the http.post
namecall: function (payload) {
return $http.post("/Api/PortalData/NameNumberResult", payload);
},
Code from the .cs controller:
public ActionResult NameNumberResult(ItemEventNameDTO payload)
{
var valuetosend = payload.itemname;
var acf = new AcFunctions();
var newstorevalue = SqlHelper.ExecuteDataset(acf.AcConn(), "sp_selectbyname", valuetosend);
payload.valuesreturned = newstorevalue.Tables[0].Rows.Count;
return payload.GetSuccess();
}
Putting a breakpoint I am getting the appropriate value from the stored procedure, either in .cs and .js files. But while trying to print the message in screen, value do not appear and "Detected undefined events having the same name" is showing instead.
Any help is welcome!
As you per your code, you are returning promise
namecall: function (payload) {
return $http.post(url, payload);
}
You need to use the callback method of $http.post()
portalRepository.namecall(payload).then(function(data){
alert("Detected: " + payload.valuesreturned + " events having the same name");
});
Related
I am trying to apply a filter to data that is being displayed on a map but for some reason, the Ajax call that I have set up is not being executed. I can reach the console.log line in the view but anything after that in the Ajax call is never executed. This is being done in ASP.NET MVC.
I have similar Ajax calls in this project from other developers that function in a similar manner. I have tried to restructure my code to work in a similar manner, but with no success. The other developers have no idea what is going on either.
C# in the controller
[HttpPost]
public ActionResult MapFilter(string filterLake, bool filterPets)
{
var filteredProperties = db.Properties.Include(a => a.PropertyCategory).Where(b => b.Status == true).Select(x => new { x.PropertyName, x.PropertyId, x.RatePerNight, x.RatePerWeek, x.MarketingTitle, x.Latitude, x.Longitude, x.Pets, x.PropertyCategory.PropertyCategoryName });
if (filterLake != "")
filteredProperties = filteredProperties.Where(a => a.PropertyCategoryName == filterLake);
if (filterPets != true)
filteredProperties = filteredProperties.Where(a => a.Pets == filterPets);
var jsonProperties = JsonConvert.SerializeObject(filteredProperties);
return new JsonResult()
{
Data = jsonProperties,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
JavaScript & Ajax in the View
var filterLake, filterPets;
var btnApplyFilters = document.getElementById("applyFilters");
var filterLakeNode = document.getElementById("filterLake");
var filterPetsNode = document.getElementById("filterPets");
$(document).ready(function () {
btnApplyFilters.onclick = function () {
filterLake = filterLakeNode.options[filterLakeNode.selectedIndex].value;
filterPets = filterPetsNode.options[filterPetsNode.selectedIndex].value;
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
$.ajax({
url: "/Estates/MapFilter",
type: "Post",
data: {
"filterLake": filterLake,
"filterPets": filterPets
},
success: function (result) {
filteredMapData = result;
console.log("Result = " + result);
loadMapMarkers(true)
}
});
};
})
When I run the program on localhost, I am able to reach the
console.log("Lake:|" + filterLake + "| Pets:|" + filterPets + "|");
line with no issues. Anything after does not run.
You need check filterPets value, it must be true/false then model binder can map with bool type.
With primitive type (bool, int, float) you should use nullable type bool? for preventing case the value incorrect format.
[HttpPost]
public ActionResult MapFilter(string filterLake, bool? filterPets)
{
}
With this paramter if filterPets has wrong value, it will be null.
May be I am not asking it in right way. I am kind of new on Tizen.
Here is my code set for tizen.
respons = tizen.filesystem.resolve("documents", function(dir)
{
file = dir.resolve("myfile.txt");
if(file.isFile){ //if file is present then fetch the information.
var res_one = file.openStream("r",
function(fs) {
var my_json = JSON.parse(fs.read(file.fileSize));
fs.close();
res_two = my_json.json_value;
return res_two;
},
function(e) {
console.log("Error " + e.message);
return null;//if there is any error then return null
}, "UTF-8");
return res_one;
}
else{
return null; //if file is not present then return null
}
});
Basically I have a file present on my display(Installed Tizen OS) that contains a json:
json_value: "My Information"
I am trying to fetch the information to use that in my javascript code. I am able to fetch that information(Checked using console.log). But it is not being returned in res_one or in response.
In short form I want to access that json outside tizen.filesystem.resolve( ...
Thanks in advance.
I have done it. Basically this is asynchronous behaviour of javascript so I have done it using call back.
function to_fetch_the_value_and_chain_process(passed_function){
tizen.filesystem.resolve("documents", function(dir){
file = dir.resolve("myfile.txt");
if(file.isFile){ //if file is present then fetch the information.
var res_one = file.openStream("r",
function(fs) {
var my_json = JSON.parse(fs.read(file.fileSize));
fs.close();
res_two = my_json.json_value;
passed_function(res_two);
},
function(e) {
console.log("Error " + e.message);
passed_function(null);;//if there is any error then return null
}, "UTF-8");
return res_one;
}
else{
passed_function(null); //if file is not present then return null
}
});
}
funtion passed_function(retrieve_res_two){
alert(retrieve_res_two );
//use retrieve_res_two and chain the next code here.....
}
to_fetch_the_value_and_chain_process(passed_function);
Hi I am trying to retrieve some data from webservice using AngularJS $http get.
I have the following code snippet:
In the servicesjs:
.factory('BoothDesignatedCoordsService', ['$http', function ($http) {
var factory = {};
factory.getBoothDesignatedCoords = function (strBoothName, intFloorPlanID) {
var sendToWS;
var boothDesignatedCoords
var JSONObj = {
BoothName: strBoothName,
FloorPlanID: intFloorPlanID
};
sendToWS = JSON.stringify(JSONObj)
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords?objJSONRequest=' + sendToWS;
return $http.get(urlBase)
}
return factory;
}])
In the controllerjs:
var boothDesignatedCoords = BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3).success(function (response, data, status) {
console.log("successfully send booth name and floor plan id to ws");
console.log("data " + data + " , status : " + status);
console.log("data " + data);
boothDesignatedCoords = data;
for (var c = 0; c < boothDesignatedCoords.length; c += 2) {
}
The $http get is successful as I am able to print "successfully send booth name and floor plan id to ws" in the browser console log.
When I tried to print console.log("data " + data), it gives me some values of an integer array. That is exactly what I want. But in the controller I tried to assign data to the variable boothDesignatedCoords, the program does not run the for loop. Am I missing some code?
EDIT:
I tried to trace the code ( trace the variable called "data" in the controllerjs) and it says "data is not defined"
You appear to be confused about the methods available on the $http promise and their arguments. Try this
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
var status = response.status
console.log('data', data) // note, no string concatenation
// and so on...
})
FYI, the success and error methods have been deprecated for some time and removed from v1.6.0 onwards. Don't use them.
I also highly recommend passing query parameters via the params config object
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords'
return $http.get(urlBase, {
params: { objJSONRequest: sendToWS }
})
This will ensure the key and value are correctly encoded.
What I want is, I want to check whether there is a file in the database or not. To do this I have a method in the controller which checks this and returns a boolean for the corresponding case. It looks like this:
public bool fileInDb(int empId)
{
using (SLADbContext db = new SLADbContext())
{
bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
if (file)
{
return true;
}
else
{
return false;
}
}
}
I simply just check if there is any file assigned to the given employee.
Now I would like to call this method from my javascript in the view, and get the return value, so that I can let the user know, if there is a file assigned to the selected employee or not. It may look like this:
$("#get-file").click(function() {
empId: $("#EmployeeSelect").val();
var fileInDb = // Get the return value from the method 'fileInDb'
if(fileInDb) {
// Let the user download the file he/she requested
var url = "#Url.Action("GetUploadedFile", "Competence")";
this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
} else {
alert("There is no file assigned to this employee.");
}
});
So my question now is, how do I get the get the return value from the method in the controller?
I would suggest few changes here:
Change your controller method to have return type ActionResult or JsonResult and I prefer JsonResult would be enough here and retrun Json response from controller and manipulate this method with $.get. You also need to change parameter to string because the parameter will be received as Json string.
public JsonResult fileInDb(string eId) //change signature to string and then convert to int
{
int empId=Convert.ToInt32(eId);
using (SLADbContext db = new SLADbContext())
{
bool file = db.CompetenceUploads.Any(x => x.EmployeeId == empId);
if (file)
{
return Json(new { result = true },JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { result = false},JsonRequestBehavior.AllowGet);
}
}
}
Now your ajax-get call would be as below:
$("#get-file").click(function() {
var eId= $("#EmployeeSelect").val();
$.get('/YourControllerName/fileInDb',{'eId':eId},function(response){
//you just need to get the response so $.get is enough to manipulate
//this will be called once you get the response from controller, typically a callback
if(response.result) //same result variable we are returning from controller.
{
// Let the user download the file he/she requested
var url = "#Url.Action("GetUploadedFile", "Competence")";
this.href = url + '?empId=' + encodeURIComponent($("#EmployeeSelect").val());
} else {
alert("There is no file assigned to this employee.");
}
})
});
You need to set-up a single page script using your ASP fileInDb function and then communicate with that page using AJAX from the browser. If you're unfamiliar with AJAX I'd recommend using the jQuery implementation to get you started.
You can use jquery and ajax to achieve this. Call your method using an ajax call from your client code. Here is an example as a reference :Calling controller method from view
In the backend create a method to call, returning a JsonResult
public JsonResult fileInDb(int empId)
{
// your code - set fileExists to true/false
JsonResult returnObj = new JsonResult
{
Data = new
{
FileExists = fileExists ;
}
};
return Json(returnObj);
}
in your javascript code use $.ajax
$.ajax({
cache: false,
url: '#Url.Action("fileInDb")',
data: { 'empId': someVar },
type: 'POST',
success: function (response) {
if (response.Data.FileExists === true) {
// do something
} else {
// it was false
}
},
error: function (er) {
alert('Error!' + er);
}
});
I have performed this action within a .js file without issue and I am wondering if I have to do something a little different from a .cshtml because I can't seem to find any other reason this is failing. Here is my js within my .cshtml file:
mergeBtn.onclick = function (e) {
e.preventDefault();
var url = '/api/publicpatron/student-no-validation?studentNo=' + studentNo.value;
$.getJSON(url)
.done(function (json) {
if (json.errors) {
toastr.error(json.message, '', { timeOut: 0, extendedTimeOut: 0 })
}
else {
//do something
}
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus = ', ' + error;
toastr.error(err, '', { timeOut: 0, extendedTimeOut: 0 })
})
}
The code in the controller doesn't seem to be the issue as it never gets to the controller, I have verified I have the controller file name and function name correct in my URL. Any suggestions? Is this not possible from within a .cshtml file??
UPDATE:
Here is the controller:
file name: PublicPatronController
[Authorize(Roles = "my-roles")]
[ActionName("student-no-validation")]
public dynamic IsStudentNoValid([FromUri] string studentNo)
{
dynamic results = new ExpandoObject();
if (studentNo == null)
{
results.error = true;
results.message = "Invalid Student Number";
return results;
}
using (ADRoutineEntities db = new ADRoutineEntities())
{
var exists = db.UserLinkages.Any(x => x.StudentNo == studentNo);
if (!exists)
{
results.errors = true;
results.message = string.Format("Student number {0} does not exist", studentNo);
return results;
}
}
results.ok = true;
return results;
}
UPDATE 2:
It does appear to be related to the controller somehow. I changed the url to a different apicontroller I use elsewhere and it worked fine. The issue seems to be related to the name of the apicontroller. When I change it to the name of an existing apicontroller but keep the actionname the same it works. Why would that be???
You should add the [HttpGet]-attribute to the method on the controller.
Normally WebAPI takes the first part of the methodname to determine what HTTP-verb it should use. In your case, that's not a valid http-method, so you need to explicitly add the attribute.
Another option is to change the method name, eg: GetIsStudentNoValid
You should also return an HttpResponseMessage with a status code instead of a dynamic