Published: 23 Jun 2010
By: Brian Mains

ASP.NET MVC makes working with AJAX really easy; it’s quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we’ll see that all here soon.

Contents [hide]

The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • Detecting an AJAX Request

    In web forms, the typical way to create AJAX requests is using an update panel; when the update panel posts back, the ScriptManager has a way to detect the AJAX postback on the server, through its IsInAsyncPostback property. ASP.NET MVC has something similar; because AJAX can invoke an action method, we need a way to detect if the request is a standard GET/POST operation, or an AJAX request.

    A helpful extension method is available to us to detect this, simply by calling Request.IsAjaxRequest(). Request is a reference to HttpRequestBase (a wrapper around the .NET 2.0 framework HttpRequest object), which is a property of the controller. IsAjaxRequest() checks the request information to ensure that an AJAX request is being made to the server, which can properly detect an ASP.NET request or a JQuery request.

    To do this, simply put the following code in your action method.

    Listing 1: Detecting an AJAX request

    Why is detecting an AJAX request important? Because you process AJAX requests differently than standard requests, depending on what the action method does. We'll see examples of this soon.

    Using the AJAX Form

    Microsoft provided a set of AJAX extensions, one of which being an Ajax form, a form that makes an asynchronous post to the server and provides a response. All of the AJAX call mechanisms on the client side are tucked into the MicrosoftMVCAjax script. A sample form is shown in Listing 2.

    Listing 2: Using the AJAX.BeginForm Extension

    The AJAX form handles the postback details, posting back asynchronously using JavaScript instead of performing a standard HTTP post to the server. In Listing 2, the form posts the data to the AjaxCustom action method, passing along the form's values, and the response is returned and utilized somehow. The Request.IsAjaxRequest method comes in handy here:

    Listing 3: Handling the Post and Providing a Response

    If an AJAX request, a special string is passed back to the client, and something is done with it. That action is controlled by the AjaxOptions collection. Listing 2 injects the "Success" message into an HTML element with the "customresponse" id. If for some reason that the request isn't from an AJAX call (an unobtrusive javascript technique), the action method can still work correctly by redirecting to another view as a fallback. We'll be covering handling these scenarios in a later article.

    I'm briefly covering this option because I believe the best option for using AJAX is JQuery.

    Using JQuery

    JQuery is very powerful; the power behind the framework comes from its simplicity and that it gives you complete control over the process. JQuery can perform a get or post operation to an MVC action method with only a few lines of client-side code. The results of the callback are given to you directly, meaning you have to control the response, but even this is very easy to do. In JQuery, we can do the following to post a form's data to the server:

    Listing 4: Posting The Form's Data

    An action method's response can be one of the following types, with the result streamed to the client. The following list

    • Content("Success") = returns the content returned as a string, which can be injected into the HTML document.
    • Json(new { a = 1 }) = returns a JSON object.
    • View("Action") = The view or partial view as an HTML string.

    These options are great because JQuery gives you raw control over the data, and you can use this data to inject into the UI or replace the UI contents entirely. Let's look at an example of each of these. I built a simple controller that returns each of these content types, as in Listing 5.

    Listing 5: Sample Content Types

    Our client will consume these action methods using JQuery, each using a separate AJAX action method that the previous. In the previous JQuery call, a post was performed, but instead, I'll perform get operations; a get and post operation is similar, except for the fact that a post passes a collection of serialized values.

    Listing 6: Loading the new data

    Of these methods, "get" and "load" work very similarly in that they can load the content directly into the HTML element; "load" injects directly without a callback, but "get" gives you more control over the handling of the data. There are a few other specialized options, like getJSON. More details on these features are available here: http://dotnetslackers.com/articles/ajax/jquery-ajax.aspx.

    This produces the following HTML output that's loaded after the document has loaded; the DIV elements below have empty inner content.

    Controlling Requests Using Attributes

    When requests are made to the server, everything about the request is inspected (headers, etc.), which is how AJAX requests are determined. Depending on how complex your applications are, you may want to separate action methods, one for AJAX requests, and another for the rest. So an index view may have an AjaxIndex action method, to process the AJAX request, and an Index action method for all other requests. We can utilize filter attributes to ensure that the correct action method gets invoked.

    The following two classes represent a filter attribute to only allow AJAX requests or standard HTTP get/post requests, respectively.

    Listing 7: Ajax/Standard Request Filter Attributes

    These filter attributes are of the action method selector kind, meaning that when the MVC framework attempts to match a request to an action method, it follows a process like the following:

    • Attempt to find an action method Index
    • Does all the existing rules pan out OK? – Yes
    • Check the filters – An Ajax only filter exists
    • Is this an AJAX request – No
    • Ignore this action method

    If, at the end of the process, no action methods exist, a resource not found response is returned from the server.

    Conclusion

    We've seen multiple uses of the MS AJAX framework and JQuery, and how easy it makes using AJAX within an MVC application. While these features exist in web forms, JQuery makes using AJAX in MVC even easier as it can directly invoke an action method and load its response into the UI. Furthermore, custom filter attributes can help identify action methods per request, or we can use the Request.IsAjaxRequest to detect the request type directly.

    The ASP.NET MVC 2 Series

  • Introduction to ASP.NET MVC 2.0 In this article, we'll begin examining the new features of ASP.NET MVC 2.0 by comparing what ASP.NET MVC offers against its predecessor, ASP.NET web forms.
  • ASP.NET MVC 2.0 User Interfaces The next part to this article series on MVC 2.0 is the user interface. We saw in the last article some basics on the changes of the user interface, which we'll delve into more in this article series. Here we will begin to look at how developers can construct the view user interface.
  • ASP.NET MVC 2.0 Using Multiple Actions Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Templating Templating is now in the ASP.NET MVC 2.0 framework, for .NET framework 3.5 and 4.0. We are going to take a look at these features.
  • ASP.NET MVC 2.0 Attributes An overview of ASP.NET MVC 2.0 Attributes.
  • ASP.NET MVC 2.0 Validation An overview of validation in ASP.NET MVC 2.0.
  • ASP.NET MVC 2.0 Areas A look at ASP.NET MVC 2.0 Areas.
  • ASP.NET MVC 2.0 and AJAX Part 1 ASP.NET MVC makes working with AJAX really easy; it's quite impressive how powerful the framework can be. JQuery adds extra features and makes AJAX calls really easy; we'll see that all here soon.
  • ASP.NET MVC 2.0 and AJAX Part 2 In this article, we are going to look at how you can utilize AJAX in your views, and utilize a concept called unobtrusive JavaScript to take advantage of a variety of situations. ASP.NET MVC provides AJAX features very easily as we previously saw, but this comes with a caveat, and it has mostly to do with the planning of the implementation. We’re going to examine these concerns in this article.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 1 In this article, we'll examine using the ADO.NET Entity Framework (ADO.NET EF). The 4.0 version has received some major upgrades, with some major API enhancements and fixes for most of the pain points within the designer.
  • ASP.NET MVC 2.0 and ADO.NET Entity Framework - Part 2 Out of the .NET framework 4.0 comes many great enhancements, the ADO.NET entity framework (ADO.NET EF) is among the top. The framework has improved upon some of the previous bugs (in version 1), as well as enhanced the API, including many new LINQ-to-SQL-like improvements. We're going to examine using these API features to create a generic version of of a data repository.
  • Complexity in ASP.NET MVC, Part 1: Dealing With Large Models At times, every developer has a web forms page or MVC view that ends up getting pretty complex, for various reasons. Whether it pulls in and integrates a lot of data (such as a portal page) or allows users to edit a lot of information, applications require data, and the amount of data grows over time. It’s a simple reality. We’re going to examine what a larger ASP.NET MVC view looks like, and some actions we can take to keep the model instantiation code as slim as possible.
  • Complexity in ASP.NET MVC, Part 2: Plan your AJAX Carefully Brian Mains discusses management of Ajax requests in ASP.NET MVC.
  • Using DI Containers in ASP.NET MVC How to use Dependency Injection containers in ASP.NET MVC.
  • Using Microsoft Unity in ASP.NET MVC Brian Mains continues his asp.net series with the unity application block.
  • <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Brian Mains

    Brian Mains is an application developer consultant with Computer Aid Inc. He formerly worked with the Department of Public Welfare. In both places of business, he developed both windows and web applications, small and large, using the latest .NET technologies. In addition, he had spent many hou...

    This author has published 73 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    jQuery Mobile Pages
    Brian Mains explains how to create pages with the jQuery Mobile framework.

    You might also be interested in the following related blog posts


    Understanding the MvcRouteHandler and MvcHandler in ASP.NET MVC read more
    Ajaxion - Standalone AJAX - Part 2 of 2 - C# and Java Example read more
    Refreshing content of the table using AJAX in ASP.NET MVC (jQuery DataTables and ASP.NET MVC integration - Part III) read more
    Refreshing content of the Datatable using Ajax in ASP.NET MVC (jQuery DataTables and ASP.NET MVC integration - Part III) read more
    Oredev Wrap-Up read more
    Introducing SharePoint 2010 Training at U2U read more
    Html Encoding Nuggets With ASP.NET MVC 2 read more
    The Underground at PDC read more
    Get Ready for Teleriks Custom-built Extensions for ASP.NET MVC read more
    10 resources to learn Moq read more
    Top
     
     
     

    Please login to rate or to leave a comment.

    Free Agile Project Management Tool from Telerik
    TeamPulse Community Edition helps your team effectively capture requirements, manage project plans, assign and track work, and most importantly, be continually connected with each other.