javascript 使用 jquery 从 .cshtml 页面调用控制器操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9330764/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:18:02  来源:igfitidea点击:

call controller action from .cshtml page with jquery

javascriptjqueryasp.net-mvc-3jquery-uirazor

提问by Laziale

I am trying to call a controller action from a jquery UI dialog. What I have currently is this:

我正在尝试从 jquery UI 对话框中调用控制器操作。我目前拥有的是:

.html("<p><textarea name=\"TextMessage\" id=\"textItems\" rows=\"10\" cols=\"72\" /><br /><br /><input type=\"button\" style=\"float:right;\" id=\"submitData\" onclick=\"Test()\" value=\"Submit\" /></p>");

The script I am using to call the controller action is this one:

我用来调用控制器操作的脚本是这样的:

<script type="text/javascript">
    function Test() {
        $ajax({
            url: '<%= Url.Action("GetData", "Report") %>',
            success: function (data) {
                alert(data);
            }
        });
    };
</script>

And the controller action is this:

控制器动作是这样的:

[HttpGet]
        public JsonResult GetData()
        {
            return Json("success", JsonRequestBehavior.AllowGet);
        }

I would like to know if I am doing something wrong, I am trying to get this to work but without any success. When I am trying directly to start the controller via http://localhost:1322/Report/GetDatait works fine, so that means that the script is not setup properly.

我想知道我是否做错了什么,我试图让它发挥作用,但没有任何成功。当我尝试通过http://localhost:1322/Report/GetData直接启动控制器时,它工作正常,这意味着脚本设置不正确。

回答by Drew Gaynor

You should try:

你应该试试:

url:'@Url.Action("GetData", "Report")'

MVC will automatically add "Controller" to the end of the second parameter when it is looking for the controller.

MVC 在寻找控制器时会自动在第二个参数的末尾添加“Controller”。

Edit:

编辑:

This code may work:

此代码可能有效:

function Test() {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: '@Url.Action("GetData", "Report")',
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert(data);
        },
        error: function(xhr, status, error) {
            alert(error);
        }
    });
}

Edit 2:

编辑2:

Changed to use Razor syntax so that this code will work with Razor/MVC3.

更改为使用 Razor 语法,以便此代码适用于 Razor/MVC3。

回答by ron tornambe

You are using MVC-2 syntax on Url.Action. This should work:

您在 Url.Action 上使用 MVC-2 语法。这应该有效:

function Test() {
  $.ajax(
    {
      url: '@Url.Action("GetData", "Report")',
      dataType: 'json',
      success: function (data) {
        alert(data);
      },
      error: function (x, err, desc) {
        alert(desc);
      }
    }
  );
};

回答by Vincenzo

You may try jsaction too: http://jsaction.codeplex.com

您也可以尝试 jsaction:http://jsaction.codeplex.com

回答by Abhishek Gahlout

We can call Controller method using Javascript / Jquery very easily as follows:

我们可以很容易地使用 Javascript / Jquery 调用 Controller 方法,如下所示:

Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'

假设以下是要调用的 Controller 方法,返回一些类对象的数组。让班级是'A'

public JsonResult SubMenu_Click(string param1, string param2)

    {
       A[] arr = null;
        try
        {
            Processing...
           Get Result and fill arr.

        }
        catch { }


        return Json(arr , JsonRequestBehavior.AllowGet);

    }

Following is the complex type (class)

以下是复杂类型(类)

public class A
 {

  public string property1 {get ; set ;}

  public string property2 {get ; set ;}

}

Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.

现在轮到 JQUERY 调用上面的控制器方法了。下面是调用控制器方法的Jquery函数。

function callControllerMethod(value1 , value2) {
    var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1  &param2=value2'
    $.getJSON(strMethodUrl, receieveResponse);
}


function receieveResponse(response) {

    if (response != null) {
        for (var i = 0; i < response.length; i++) {
           alert(response[i].property1);
        }
    }
}

In the above Jquery function 'callControllerMethod'we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.

在上面的 Jquery 函数“callControllerMethod”中,我们开发了控制器方法 url 并将其放入名为“strMehodUrl”的变量中,并调用 Jquery API 的 getJSON 方法。

receieveResponseis the callback function receiving the response or return value of the controllers method.

receieveResponse是接收控制器方法的响应或返回值的回调函数。

Here we made use of JSON , since we can't make use of the C# class object

这里我们使用了 JSON ,因为我们不能使用 C# 类对象

directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:

直接进入javascript函数,所以我们将控制器方法中的结果(arr)转换为JSON对象,如下所示:

Json(arr , JsonRequestBehavior.AllowGet);

Json(arr , JsonRequestBehavior.AllowGet);

and returned that Json object.

并返回该 Json 对象。

Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.

现在在 Javascript / JQuery 的回调函数中,我们可以利用这个结果 JSON 对象并相应地在 UI 上显示响应数据。

For more detail click here

欲了解更多详情,请点击此处

回答by Craig

Because you are calling an action method that is returning a jsonobject you can use the jQuery.getJSON()method.

因为您正在调用返回json对象的操作方法,所以您可以使用jQuery.getJSON()方法。

<script type="text/javascript">
    function Test() {
        $.getJSON(
            '@this.Url.Action("GetData", "Report")',
            function (data) {
                alert(data);
            }
        });
    };
</script>