Calling MVC Actions from Javascript

Suppose we have a very simple action method: it takes no parameters and just returns a string:

What if we would like to call this action method from javascript through Ajax and to display the value it returns? We can do it with jQuery:

Not so bad, after all. However, let think, about all implications of the above simple raw approach to the interaction with an action method:

  1. Repeating the above code several times in an application is annoying, and error-prone.
  2. We have no access to Razor helpers from within js files, so we can’t use @Url.Action, and other similar methods to compute the Url we need.
  3. The code depends on the action method being marked  as HttpPost or HttpGet. Each time we modify these attributes we have to go through all our js files that might contain references to the action method and change them.

Are there a better ways to interact with an action methods that doesn’t suffer of the above problems? There are some:

  1. We can pack all information that define the details of the call into a standard option object and we may simply write something like:

  2. There are extensions, like RazorJs, that enable us to write Razor syntax into Js files (—write-razor-inside-your-javascript-files)
  3. Actually problem 3. this is not easy to solve….

However, is there a way to solve all the above problems together? This lead me to conceive JsAction.
Well, now that the we made the problem clear, we are ready to go through JsAction and see how it can help us. JsAction can be installed in 2 ways:

  1. By downloading the library from download page and by referencing it in Visual Studio
  2. By using the NuGet package manager and adding the JsAction package.
    Go to Tools -> Library Package Manager -> Add Library Package Reference and select OnLine. Once located the package press install.

You just need to add script references  to the pages that use it. This is easily accomplished by placing the reference into the layout pages (usually your layout.cshtml). It must be called after the jQuery reference:

NOTE: script.js is not a part of the libray but just the example javascript file that needs to call the action method. Clearly we must place it after the jsAction reference.
Simple Usage
Once configuration is done, we can use JsAction. Let’s take the usual Home controller class and let decorate the methods we would like to call from the client with JsAction attribute:

For sake of simplicity let’s use just the default parameterless costructor, further options can be found in the documentation. JsAction  creates a JsActions object containing all methods we marked with the JsAction attribute. Now we are ready to use them from Javascript code with the pattern JsAction.ControllerName.Method:

Where “ret” is the object returned by the $.ajax call.
According to the jQuery documentation:

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object.


The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface
This means, if we are using jQuery 1.5+, we can take advantage of the Promise interface:

What if i’m using jQuery < 1.5?
Well, …we can still set all usual jQuery ajax call options, since all methods created by JsAction takes an optional option parameter, that is merged with the jQuery ajax call options(see the jQuery ajax documentation –> ),  Thus, our previous example becomes:

Summing up JsAction provide a quick and easy way to map  server side methods into client side methods in  1:1 fashion. Visual Studio provides a smart intellisense support not only for .NET languages (C#, Vb.NET), but also for JavaScript (see the new ide features ). The good news is that jSAction not only imports in javascript the action methods, but also the the help encoded into the action methods comments:
Let’s  experiment this by writing a simple class and an action method marked with the JsAction attribute…. and by adding some server side “help comments” on this action method:


Visual Studio provides a smart intellisense support

Now let run the application and let verify carefully that it actually compile and runs, since the Doc generation feature requires that

  • The application compiles.
  • The application runs.
  • The Xml output file is enabled (Project Properties -> Build -> Check “Xml Documentation File”).

Now we’re ready to generate automatically the javascript documentation. Go to Tools->Library Package Manager-> Package Manager Console
generate automatically the javascript documentation
Once opened we just have to write
PM> JsAction-GenDoc
The project will be built and run. If any error occurs, it will be displayed in the console.
Please just wait without interacting with the console until the project close automatically. Then lets go to the Solution Explorer and let give a look to the script folder
go to the Solution Explorer
A new file has been added: JsAction documentation file. It contains unmodified and commented javascript code.

Now let’s create a new javascript file and use the doc file as reference.
Code completion
Code completion
Code comments!!
Code comments
As you can see from the second image, also the parameter types are resolved. (Student,Int32). This should help you to never use a wrong type.
The Intellisense feature will work also if no Xml Documentation file generation is enabled. However, it will miss YOUR comments, providing only method signature and type resolution.
Please Notice, the vsdoc file must never be used as a @JsScript call replacement. It misses internal functions and it’s purpose it’s only to documentate function during development.
JsAction has also a basic WebApi support.
Below an ApiController decorated with the JsAction attribute

The above controller implements just a simple CRUD logic. As you can see the JsAction attribute is applied to the whole class instead of on the Action Methods. In fact in this case of ApiControllers, substantially, all methods are created to be called from javascript, so it make no sense to decorate only some methods.
Anyway, since all methods decorated with NonActionAttribute are not intended to be exposed on the Web no javascript method is created for calling them.
All WebApi methods are placed into the JsActions.WebApi namespace. Below the unit test results of the first controller, and the an example of usage:


JsActions.WebApi namespace
JsAction, when needed, performs also a Complex Type Decomposition:.
Complex Type Decomposition
As you can see from the image image above, if a method  has complex types as parameters, then JsAction creates  javascript proxies for the with full intellisense support.
Blog posted on a special request of my friend Vincenzo(

Tagged , . Bookmark the permalink.

One Response to Calling MVC Actions from Javascript

  1. Pablo says:

    I have only started using Visual Studio a few weeks. I think the post and the links were interesting, but a little too advanced for me. Is there a link you can post about tutorials for beginners? Thanks!

Leave a Reply

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