Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 5 calling controller method from Javascript Error

I am attempting to call a controller method from javascript and I seem to be having trouble getting this to execute correctly. I have very little experience with javascript and have followed other examples of how to do this from stackoverflow but I am still having some issues- if anyone can help that'd be fantastic.

Basically what I am trying to do is set a .data tag on a javascript object to the string returned by a method on the controller (this method calls a webservice that runs a SQL Server function). The method needs to be passed one parameter which is used in the function.

The code is 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 the NodeController- which is what I am referring to in url: call of ajax.

Basically what is happening is when i run the page, I first get an error saying it cannot set this.node.fill to a null value THEN I get the alert that an error occurred- like I said I am pretty inexperienced with javascript so I am honestly not even sure if it is calling the method in the correct order if i get an error on this.node.fill before I receive the error message from JQuery.

Any/all help or suggestions is greatly appreciated!!!

like image 483
jhinx Avatar asked Jan 05 '15 17:01

jhinx


2 Answers

  1. If your controller class is NodeController, use only "Node" for the controller name in Url.Action:

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

  3. We don't know what this.node.fill is or where it is defined. Likely, this.node is not defined at the time the assignment is executed.

like image 193
Igor Avatar answered Sep 28 '22 05:09

Igor


You need not to write controller with controller's name

@Url.Action("CallService", "Node")
like image 45
Tushar Avatar answered Sep 28 '22 05:09

Tushar