Unobtrusive Ajax in ASP.NET MVC

ASP.NET MVC Framework has built-in Ajax enabled helper methods for unobtrusive Ajax support, which simplify the process for Ajax calls in your MVC Web Applications. Those Ajax methods are based of course in jQuery, so if you are familiar with the latter, learning to use them will be a piece of cake. We have shown the tranditional way to make Ajax calls in MVC applications in previous post. This post will guide you step by step showing you an alternative and more straight forward way to make Ajax calls through the built-in helper methods which eliminates the need to add blocks of code in your Views. Let’s start.

Start by creating a new ASP.NET MVC Web Application named “MVCUnobtrusiveAjax”, choosing the Basic template and Razor for view engine. We will create first our domain model. Create a C# class file named “Product.cs” in your models folder. Add a Product class and a Category enumeration as follow.

This class uses some mock Product objects and has two basic operations, the GetProducts() and the GetProducts(String selectedCategory). The first one, will display all available products while the second one, the selected category’s only. Right click inside a GetProducts action and add a View with the same name. Fill IEnumerable<Product> in the Model class (Strongly-typed View).

The Html.BeginForm() helper method, ensures that the form will post back to the [HttpPost] GetProducts action method the selectedCategory value. Before running your application you may want to change the default routing values for the controller and action segments in the RouteConfig.cs file like this.

This way when your start your application you will redirected immediately to the following View.

At this time, your application works fine, you can select a category, click the Submit button and get the respective results. Though, Unobtrusive Ajax isn’t supported yet, hence you get a full page reloading. To enable it, make sure you have a key=”UnobtrusiveJavaScriptEnabled” value=”true” in your root Web.config file under the appSettings element.

Then add jQuery support in the central _Layout.cshtml file. Remove the script sections and style sections and add two references from your script folder. You may have different versions on your scripts folder, so make sure you use the right ones.

We are going to use the GetProductData to render a partial View which will update our table rows according to the selected category. On the other hand, the GetProducts action method now will just pass to the View the selectedCategory value. This way we simplified our code removing the [HttpPost] attribute. Now we have to create our Partial View which will update the table contents. Right click in the GetProductData action and add a Partial View with strong-type IEnumerable<Product>. Paste the following contents.

Still your application works fine but not Ajax asynchronous calls. Though we render our table contents through an action method which return a partial View. It’s time to enable the Unobtrusive Ajax in our View. Change the GetProducts contents again, like this.

Build and run your applications. Select a category and ensure that this time you get your results asynchronously. What we did above is to use an Ajax.BeginFrom Ajax helper method which takes the target action method to invoke and an AjaxOptions object parameter. We configured this object in 5-8 requesting the returned data to replace the “UpdateTargetId” tbody element. So simple. If you want to provide the user with a feedback while making the ajax request you can do it this way.

Clicking OK will proceed the Ajax request while selecting Cancel will cancel it. We have used an Ajax.BeginForm helper method to pass the category value in the GetProductData action. What if we wanted to make the same thing through links? You can do this using the Ajax.ActionLink helper method like this.

Click a category link and notice that you get the same Ajax result. The last thing I wanna show you is the CallBack functions OnBegin, OnSuccess, OnFailure, OnComplete. Add a script with functions in the GetProducts View and bind them to the Ajax links through the AjaxOptions as follow.

Click a Category link and pay attention to the Ajax request life-cycle.

That’s it, this is the way to use Unobtrusive Ajax in ASP.NET MVC applications. In later post, we ‘ll see how to get JSON data from your actions methods when using Unobtrusive Ajax. You can download the MVCUnobtrusiveAjax project we have created from here.

In case you find my blog’s content interesting, register your email to receive notifications of new posts and follow chsakell’s Blog on its Facebook or Twitter accounts.

12 replies

I would like to thank you for the efforts you have
put in writing this site. I really hope to check out the same high-grade blog posts by you later on as well.
In truth, your creative writing abilities has inspired
me to get my own blog now 😉

I was so frustrated prior to working through your article. I even started reading your article and said “No – this doesn’t work!”. But then I stopped. I thought – This guy wouldn’t have made an article like this without having it working… So, I went back to basics. I followed each of your steps, duplicating them on my end as I went. Success.

Thanks for the posting this article, but I have some issues while duplicating the steps you mentioned above.
I am new to ASP.NET MVC and I was having problem with AJAX. I came across your article and followed each and every step, but still when I click submit, the partial view is rendered on a new page rather than on the same page.

Hi there! I could have sworn I’ve been to this website before but
after browsing through some of the post I realized it’s
new to me. Anyways, I’m definitely happy I found it and I’ll be
bookmarking and checking back frequently!

The purpose of this blog is to broaden my education, promote experimentation and enhance my professional development. Albert Einstein once said that “If you can’t explain it simply, you don’t understand it well enough” and I strongly believe him!