ASP。NET MVC 5從Javascript錯誤調用控制器方法

[英]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.

基本上,我要做的是將javascript對象上的.data標記設置為控制器上的方法返回的字符串(該方法調用運行SQL Server函數的webservice)。該方法需要傳遞函數中使用的一個參數。

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) {
        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


    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.

這個控制器被稱為NodeController—我在url: 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!!!


2 个解决方案



  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 -

    不能從異步函數同步返回值。要么將回調傳遞給調用服務,在成功時調用它,要么使用jquery 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.




You need not to write controller with controller's name


@Url.Action("CallService", "Node")



粤ICP备14056181号  © 2014-2021