ASP.NET MVC Partial Updates Using Unobtrusive Ajax And JQuery

Ajax allow web pages to exchange data asynchronously with the server in order to update specific portions of the page rather reloading its entire content. This will enhance the responsiveness and performance of the web applications. ASP.NET MVC affords multiple approaches to implement this behavior by requesting or submitting data to partial pages. In this article, we will talk about two approaches to accomplish: Unobstrusive Ajax and JQuery Ajax.

Firstly, we will start creating the project and all the code needed to implement the asynchronous behavior. After that we will start explaining both the approaches:

Step 1: Create a new ASP.NET MVC project:

new ASP.Net MVC Project

Step 2: Select a Basic Project Template:

Basic

Step 3: Add a new class Book to your Models

Select a Basic Project Template

Step 4: Create the BooksRepository (it’s an in-memory repository that keeps all our library of books, from where we will retrieve our sample data)

BooksRepository

Step 5:
Add New Controller: BooksController (in the Controllers folder)

BooksController

Step 6: Create the action “BooksSearch” that will search for books and return our partial view:

Add New Controller

Step 7: Create a new folder which will hold our views “Books” in the “Views” Folder.

Step 8: Create the partial view “BooksSearch” (with the same name of our action method). The Ajax functions will call this partial view to update a portion of the page and avoid the browser refreshing the entire html document.

action method

Step 9: Add the html that will show the books resulting from searching the partial view “BooksSearch”.

BooksSearch

Step 10: Add an “Index” view (in Views \ Books folder) that will contain our asynchronous search functionality:

asynchronous search

Step 11: The Solution Project will look like the following screenshot,

Index

Now returning back to the “Index”view to implement the search functionality using the two approaches:

Using Unobtrusive Ajax

This approach allows us to use a strategy known as progressive enhancement which focuses on the delivery of content. It follows the same practice ASP.NET MVC which is separation of concern by trying to separate the markup responsible for the view from JavaScript code. It make Ajax calls through the built-in helper methods which eliminates the need to add blocks of JavaScript code in our Views and makes source code cleaner, readable and improves the performance since the browser needs only the downloadable js library (which can be cached).

Step 1: Install the “jquery.unbrotusive-ajax” using Visual Studio NuGet Manager and if it doesn’t exist (By default MVC 4 includes it in the Scripts folder)

jquery.unbrotusive

Step 2: In the Index view which resides in Views / Books, we will implement the functionality using Ajax.BeginForm that will perform asynchronous request to the server. This method take several arguments:

  • Action name: “BooksSearch” action that will query the books repository and return the partial view “BooksSearch.cshtml”.
  • An instance of AjaxOptions: It holds the settings of the asynchronous request:

    • HttpMethod: Specify the Http request method “GET” or “POST”.

    • InsertionMode: How to insert the response in the target element (“Replace”, “ReplaceWith”).

    • UpdateTargetId: The element in the view that will be replaced with the response coming back from the server.

  • A JavaScript function to call if one of the events occurs:

    • OnSuccess: Called after the page is updated successfully.
    • OnFailure: Called after failing to update the page.
    • OnComplete: Called when response data has been instantiated but before the page is updated.
    • OnBegin: Called immediately before the page is updated.

In our example, we are going to retrieve the data from the server using the “GET” method, replace the response with the dom element that has the Id “booksSearchResult” and ask to replace it. We will also display a meaningful message to the user if certain error happens while searching. So, we will add the OnFailure event and specify the method. It shall call “failedSearch” which is defined in the same view.

jquery

The jquery.unobtrusive library should be included in the page.

Step 3: Now, we can run the application and show how the Ajax search will retrieve our results and update the page.

Ajax search

Taking a look on the source of the page (right click page in the browser -> View page source), we notice that there are no scripts added (less code), just HTML5 attributes on the rendered form (such as: data-ajax-method, data-ajax-update) that affords readability and adhering to web standards.

  1. <formaction="/Books/BooksSearch" data-ajax="true" data-ajax-failure="failedSearch" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#booksSearchResult" id="form0" method="post">  
  2.     <inputtype="text" name="title" />  
  3.     <inputtype="submit" value="Search Books" /> </form>  
  4.     <divid="booksSearchResult">  
  5.     </div>  
Using JQuery Ajax

This approach affords more flexibility, requires more script writing, but doesn’t need additional external scripts (just like the jQuery library).

Step 1: We will declare our form and specify the ids for all our controls in order to reference them using JQuery.

Script

Step 2: Then, we will write a handler for form submission, and use “ajax” method to send a request to our action method.

Using Ajax function, we can achieve all the functionalities provided by Ajax Helper. This function expects the following arguments:
  • url: Url to send the request for, in our example will request data from the action “BooksSearch”.

  • type: The HTTP method to use for the request (e.g. "POST", "GET", "PUT").

  • data: Parameters passed in the request. Our action expects the parameter “title”, so get the value from the textbox and pass it as argument named “title”.

  • success: Callback function that is called if the request succeeds. Get the data returned from the request and update the div content to show the results returned.

  • failure: Callback function that is called if the request fails. We will call “failedSearch” function which display a friendly message to the user.

    Code
We have applied the two approaches to implement Ajax requests to controller actions and update our pages. We can notice that the first one is easier to implement when a developer is more comfortable working with C# and the second requests more scripting and provides more flexibly without including additional libraries.


Similar Articles