How to call a controller action by jQuery

With jQuery you are able to invoke an action of a Asp .Net MVC application's controller.
This is the code you need:

   1:  $.ajax({
   2:      url: 'Controller/Action?parameter1='+parametervalue,
   3:      parameter1: parametervalue,
   4:      type: 'GET',
   5:      async: false,
   6:      cache: false,
   7:      success: function(data){
   8:      alert('Action called successfully');
   9:       }
  10:  });

You can establish the request type (GET, SET and so), whether the request should be asynchronous or not (parameter async true or false), whether the request should be cached or not (parameter cache), a Javascript function to be called in case of success of the server request (parameter success) or in case of request fails (parameter error).
The parameter "data" of the function called in case of success contains the return value by the server call.

However there are many others useful parameters you can use. For a complete list go here. It's also possible to make the same call but with a Json return value by the $.getJSON funtion.

Print | posted on Wednesday, March 16, 2011 6:16 PM

Comments on this post

No comments posted yet.

Your comment:

 (will show your gravatar)
Please add 4 and 5 and type the answer here: