Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

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

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

Thanks.

like image 268
Erick Garcia Avatar asked May 25 '11 03:05

Erick Garcia


People also ask

How do you call a controller action in JavaScript?

The Controller's Action method is called using JavaScript XmlHttpRequest (XHR) AJAX request and the value of the TextBox is passed as parameter and the returned response is displayed using JavaScript Alert Message Box.


4 Answers

You can start reading from here 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.

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

like image 56
rob waminal Avatar answered Sep 29 '22 10:09

rob waminal


the previous response is ASP.NET only

you need a reference to jquery (perhaps from a 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.

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

like image 30
Glenn Ferrie Avatar answered Sep 29 '22 11:09

Glenn Ferrie


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

Suppose following is the Controller method to be called returning an array of some class objects. Let the class is '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.

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.

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

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

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

Json(arr , JsonRequestBehavior.AllowGet);

and returned that Json object.

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.

For more detaill click here

like image 24
Abhishek Gahlout Avatar answered Sep 29 '22 10:09

Abhishek Gahlout


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

Note in this example my controller name is Student

Controller Action

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

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

<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>
like image 21
yogihosting Avatar answered Sep 29 '22 11:09

yogihosting