如何在 ASP.NET MVC 中使用 JQuery 调用控制器动作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6119098/
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-08-26 20:25:51  来源:igfitidea点击:

How to Call Controller Actions using JQuery in ASP.NET MVC

jqueryasp.net-mvcajax

提问by Erick Garcia

I've been reading on this for a while and found that you can call a controller action by using:

我已经阅读了一段时间,发现您可以使用以下方法调用控制器操作:

$.ajax("MyController/MyAction", function(data) {
    alert(data);
});

Does this mean I should add the MicrosoftMvcAjax.js or the MicrosoftAjax.js along with the Jquery lib?

这是否意味着我应该将 MicrosoftMvcAjax.js 或 MicrosoftAjax.js 与 Jquery 库一起添加?

Also, what should the second parameter contain in the $.ajax() function?

另外,$.ajax() 函数中的第二个参数应该包含什么?

Lastly, any other link in stackoverflow or outside of the site that could be helpful in asp.net mvc w/ ajax and jquery?

最后,stackoverflow 中或站点外部的任何其他链接可能对 asp.net mvc w/ajax 和 jquery 有帮助?

Thanks.

谢谢。

回答by rob waminal

You can start reading from here jQuery.ajax()

你可以从这里开始阅读jQuery.ajax()

Actually Controller Action is a public method which can be accessed through Url. So any call of an Action from an Ajax call, either MicrosoftMvcAjax or jQuery can be made. For me, jQuery is the simplest one. It got a lots of examples in the link I gave above. The typical example for an ajax call is like this.

实际上Controller Action是一个可以通过Url访问的公共方法。因此,可以从 Ajax 调用(MicrosoftMvcAjax 或 jQuery)调用任何 Action。对我来说,jQuery 是最简单的。它在我上面给出的链接中有很多例子。ajax 调用的典型例子是这样的。

$.ajax({
    // edit to add steve's suggestion.
    //url: "/ControllerName/ActionName",
    url: '<%= Url.Action("ActionName", "ControllerName") %>',
    success: function(data) {
         // your data could be a View or Json or what ever you returned in your action method 
         // parse your data here
         alert(data);
    }
});

More examples can be found in here

更多例子可以在这里找到

回答by Glenn Ferrie

the previous response is ASP.NET only

之前的响应仅适用于 ASP.NET

you need a reference to jquery (perhaps from a CDN): http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

您需要对 jquery 的引用(可能来自 CDN):http: //ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js

and then a similar block of code but simpler...

然后是一个类似的代码块,但更简单......

$.ajax({ url: '/Controller/Action/Id',
         success: function(data) { alert(data); }, 
         statusCode : {
             404: function(content) { alert('cannot find resource'); },
             500: function(content) { alert('internal server error'); }
         }, 
         error: function(req, status, errorObj) {
               // handle status === "timeout"
               // handle other errors
         }
});

I've added some necessary handlers, 404 and 500 happen all the time if you are debugging code. Also, a lot of other errors, such as timeout, will filter out through the error handler.

我添加了一些必要的处理程序,如果您正在调试代码,404 和 500 会一直发生。此外,许多其他错误,例如超时,将通过错误处理程序过滤掉。

ASP.NET MVC Controllers handle requests, so you just need to request the correct URL and the controller will pick it up. This code sample with work in environments other than ASP.NET

ASP.NET MVC 控制器处理请求,因此您只需要请求正确的 URL,控制器就会接收它。此代码示例适用于 ASP.NET 以外的环境

回答by yogihosting

You can easily call any controller's action using jQuery AJAX method like this:

您可以使用 jQuery AJAX 方法轻松调用任何控制器的操作,如下所示:

Note in this example my controller name is Student

请注意,在此示例中,我的控制器名称是Student

Controller Action

控制器动作

 public ActionResult Test()
 {
     return View();
 }

In Any Viewof this above controller you can call the Test()action like this:

在上述控制器的Any View中,您可以像这样调用Test()操作:

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
    $(document).ready(function () {
        $.ajax({
            url: "@Url.Action("Test", "Student")",
            success: function (result, status, xhr) {
                alert("Result: " + status + " " + xhr.status + " " + xhr.statusText)
            },
            error: function (xhr, status, error) {
                alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            }
        });
    });
</script>

回答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 方法。

receieveResponse is 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);

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 detaill click here

更多详情请点击这里

回答by user2284063

In response to the above post I think it needs this line instead of your line:-

为了回应上面的帖子,我认为它需要这条线而不是你的线:-

var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' &param2='+value2

Or else you send the actual strings value1 and value2 to the controller.

否则,您将实际字符串 value1 和 value2 发送到控制器。

However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.

但是,对我来说,它只调用控制器一次。它似乎每次都点击“receieveResponse”,但控制器方法上的断点显示它仅在页面刷新前第一次点击。



Here is a working solution. For the cshtml page:-

这是一个有效的解决方案。对于 cshtml 页面:-

   <button type="button" onclick="ButtonClick();"> Call &raquo;</button>

<script>
    function ButtonClick()
    {
        callControllerMethod2("1", "2");
    }
    function callControllerMethod2(value1, value2)
    {
        var response = null;
        $.ajax({
            async: true,
            url: "Logging/SubMenu_Click?param1=" + value1 + " &param2=" + value2,
            cache: false,
            dataType: "json",
            success: function (data) { receiveResponse(data); }
        });
    }
    function receiveResponse(response)
    {
        if (response != null)
        {
            for (var i = 0; i < response.length; i++)
            {
                alert(response[i].Data);
            }
        }
    }
</script>

And for the controller:-

对于控制器:-

public class A
{
    public string Id { get; set; }
    public string Data { get; set; }

}
public JsonResult SubMenu_Click(string param1, string param2)
{
    A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
    return Json(arr , JsonRequestBehavior.AllowGet);
}

You can see the time changing each time it is called, so there is no caching of the values...

您可以看到每次调用时时间都在变化,因此没有缓存值...