Simple and painless Ajax in MVC3

by trouf on 27/04/2011

Even though Microsoft really came through with MVC3 and added a lot of sweetness, I still find myself reluctant to use the provided Ajax-functionality.

Here’s why:

This approach is nice and simple, yes. But what if I don’t like having global javascript functions all over the place to handle the results of the action. It kind of pains me to see that I can use ”unobtrusive” validation functionality in MVC3 but not unobtrusive Ajax handling.

This is solved by implementing the ”ajaxification” of a normal Html.ActionLink in a separate javascript,
such as proposed here http://stackoverflow.com/questions/4878127/mvc3-ajax-actionlink.

I needed a more reusable way of doing this, but portable enough to be painlessly lifted to other projects and easy to use for other developers in the project. So i slapped together this jQuery plugin…

Using it is quite straightforward, or at least it seems to me at the time of writing this.

First, we create the controller action that we want to call with the Ajax link:

This action returns a view, so a view will have to be created as well. A simple plain text partial view will do fine. Be sure not to load any layout for this though. The action could have returned JSON as well,
as both cases can be handled by the jQuery plugin.

With a controller action and a view in place, we create the ActionLink in the view where we need the Ajax functionality:

There we go!, now we can declare all our events and handlers well outside the view layout as demonstrated in the following gist:

stefan.pataky@gmail.com

No comments yet.

Write a comment: