Erick Garcia Erick Garcia - 6 months ago 78
Javascript Question

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.

Answer

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