ASP.NET MVC 5 controller method call from Javascript Error

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 !!!

+5
source share
2 answers
  • If your controller class is NodeController , use only "Node" for the controller name in Url.Action :

     url: '@Url.Action("CallService", "Node")', 
  • You cannot synchronously return a value from an asynchronous function. Either pass the callback to CallService to be called, or use the jquery promise - http://api.jquery.com/promise/

  • We do not know what this.node.fill , or where it is defined. Probably this.node not defined during the execution of the job.

+5
source

You do not need to write a controller with the name of the controller

 @Url.Action("CallService", "Node") 
+2
source

Source: https://habr.com/ru/post/1210416/


All Articles