I am trying to call a controller method from javascript and it seems to be having problems with it working correctly. I have very little experience with javascript, and I have followed other examples of how to do this from stackoverflow, but I still have some problems - if someone can help, this will be fantastic.
Basically what I'm trying to do is set the .data tag in the javascript object to the string returned by the controller method (this method calls the web service that runs the SQL Server function). The method must be passed one parameter, which is used in the function.
Code below:
Javascript Code
for (var i = 0; i < stats.length; i++) { var stat = stats[i].data('id'); var color = CallService(stat); this.node.fill = color; }
JQuery Method
function CallService(id) { $.ajax({ url: '@Url.Action("CallService", "NodeController")', type: 'GET', dataType: 'json', cache: false, data: { 'id': id }, success: function (color) { return color; }, error: function () { alert('Error occured'); } }); }
Controller method
[HttpGet] public JsonResult CallService(string id) { var idNum = Convert.ToInt32(id); var StationService = new getStationStatus.Service1SoapClient("Service1Soap"); string color = StationService.getStationStatus(idNum); return Json(color, JsonRequestBehavior.AllowGet); }
the controller is called NodeController, which I mean in url: ajax call.
Basically what happens when I start the page, I first get an error saying that it cannot set this.node.fill to zero. THEN I get a warning that an error has occurred. As I said, I'm pretty inexperienced with javascript, so I'm honestly not even sure if it calls the method in the correct order, if I get this.node.fill error message before I get the error message from jQuery.
Any / all help or suggestions are greatly appreciated !!!