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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>