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

时间:2021-07-11 04:14:03

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。Jquery lib支持js吗?

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

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

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

最后,在*或者站点之外的任何其他链接对asp.net mvc w/ ajax和jquery有帮助吗?

Thanks.

谢谢。

5 个解决方案

#1


39  

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操作是一种可以通过Url访问的公共方法。因此,任何来自Ajax调用的动作调用,无论是MicrosoftMvcAjax还是jQuery,都可以进行。对我来说,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

更多的例子可以在这里找到

#2


28  

the previous response is ASP.NET only

前面的响应是ASP。网只

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之外的环境中工作

#3


1  

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'

假设下面是要调用的控制器方法,返回某个类对象的数组。让这个类是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调用上面的控制器方法了。下面是调用controller方法的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是接收controller方法的响应或返回值的回调函数。

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函数,将controller方法中的结果(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

更多详情请点击这里

#4


1  

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

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

#5


0  

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 View of this above controller you can call the Test() action like this:

在上述控制器的任何视图中,都可以调用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>

#1


39  

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操作是一种可以通过Url访问的公共方法。因此,任何来自Ajax调用的动作调用,无论是MicrosoftMvcAjax还是jQuery,都可以进行。对我来说,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

更多的例子可以在这里找到

#2


28  

the previous response is ASP.NET only

前面的响应是ASP。网只

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之外的环境中工作

#3


1  

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'

假设下面是要调用的控制器方法,返回某个类对象的数组。让这个类是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调用上面的控制器方法了。下面是调用controller方法的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是接收controller方法的响应或返回值的回调函数。

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函数,将controller方法中的结果(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

更多详情请点击这里

#4


1  

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

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

#5


0  

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 View of this above controller you can call the Test() action like this:

在上述控制器的任何视图中,都可以调用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>