Published: 13 Sep 2010
By: Brian Mains

Brian Mains discusses management of Ajax requests in ASP.NET MVC.

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.
  • Introduction

    ASP.NET web forms chose the option of communicating with web services as its mode for communication between client-side JavaScript and server-side code. A web service, using the ScriptService attribute, can render a client-side proxy to call these web methods, provided that it doesn't go outside the bounds of the current web domain (a browser restriction).

    ASP.NET MVC differs from this methodology a bit; instead of using web services, client-side code can directly invoke an action method. This means all of the code can reside in a controller, but be invoked in various ways, either by client-side JavaScript or a direct URL request.

    What this can mean is that controllers may container a lot of mixed code serving different purposes. Action methods may need to render the entire view or only render part of it. Either way, it's important to develop a strategy to handle it.

    Understanding the Problem

    Let's look at what I'm trying to illustrate. Suppose we have this action method:

    Listing 1: Serving the View

    If the browser requests this view, an ASPX page serves the request through the associated view. However, if JQuery requests the action method as in Listing 2, this is an entirely different type of request.

    Listing 2: Using JQuery

    We can return the full view, but usually JQuery only needs to replace a portion of it. Typically, setting up a partial view to replace via JQuery is a better approach because we can swap out one set of content for another, essentially. Previously, we talked about how to use the Request.IsAjaxRequest extension method to check for AJAX requests, how to invoke views via JavaScript, and setup complex action methods. Here we are going to look at that level of planning AJAX in MVC.

    Sample Scenario

    Let's envision a sample scenario in order to properly explain how to solve the problem. We have a shopping cart. The shopping cart allows a user to update or delete an item within it, as well as calculate the subtotal, estimate the shipping, give us a grand total, process payment transactions, and more.

    Some of the concerns we have to have is:

    • Which of the actions are AJAX-based actions, and which will invoke a full postback?
    • Does a single action need to manage both AJAX and non-AJAX requests?
    • If an update action works with both AJAX and non-AJAX requests, does this happen in the same method, or are there split methods for this action? For a non-AJAX request, the data must be reloaded and returned with the same shopping cart view name. Will this cause headaches later?

    Single Action Methods

    Having a single action method handle AJAX and standard requests can meet the demand. For instance,the following action method can serve up both types of requests:

    Listing 3: Handling AJAX and Standard Requests in One Action

    Here one method serves both requests. This structure works well if we have one AJAX callback to the server, say for posting back the data to the server or refreshing the UI. However, this naturally doesn't work well whenever we have more than two requests on a single view. If a view uses Html.Action or gets or posts data several times to the server, the next option might be better.

    Handling Requests in Separate Callbacks

    If, instead of requesting data from the same action, using separate actions for AJAX only features is a viable option. That way, for example, a shopping cart action can render the view, but each update or delete operation that happens through AJAX is a separate action method.

    What if we used the code in Listing 4, using different action method to represent different actions to take, and each one was responsible for handling the difference between a standard request or AJAX request?

    Listing 4: Multiple Callbacks

    The dilemma here is that each of the action methods is responsible for dealing with full-postbacks as well. For instance, when an update happens, either via AJAX or not, it invokes /Shopping/Update. When that request is an AJAX request, it only needs to return a partial view, content, or JSON data to the caller. When a standard request, the server needs to serve up the entire view, and as such, the Update and Delete actions also return the ShoppingCart view.

    This approach can be cumbersome. If anything changes with the shopping cart, all changes must now be replicated three times. It may be tempting to do this:

    Listing 5: Invoking the Action Directly

    Note that the full postback invokes the action method directly. However, this doesn't quite work like we would expect. Since no view name is specified, it uses the current view (update) and produces the wrong response. Instead, the RedirectToAction result might be the best option because it would give the ShoppingCart action the full responsibility for handling the complete load. Note, however, that this might affect the current navigation of the application, and that is also a concern.

    Handling AJAX Callbacks With Separate Controller

    Alternatively, AJAX requests could be made using actions in a separate controller. This might be a decent separation of standard/AJAX requests. For instance, if we had a ShoppingController, a ShoppingAjaxController can serve up the AJAX requests. To reproduce our update/delete actions above, the following code contains the updated code in multiple controllers.

    Listing 6: Using Two Controllers

    This gives us a greater level of separation, as the code within an action method can be a lot if attempting to handle both types of request in the same method. This splits out the UI logic nicely. However, we have a new dilemma, because we are duplicating the processing logic twice!

    To handle that duplication, the application could refactor the logic out into a separate class, and use that class to do that work.

    Conclusion

    The ASP.NET MVC framework provides a lot of power to the developer, and we have to ensure that the applications we build are maintainable and efficient. Splitting standard and AJAX requests to be served by different action methods gives us some benefits, but requires some additional care. This article discussed a few alternatives, including putting all of the logic within the same action method, using separate action methods for each request type, or using separate controllers.

    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...
    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 ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.

    You might also be interested in the following related blog posts


    MvcContrib working on Portable Areas read more
    More On The CodePlex Foundation read more
    ASP.NET MVC and the templated partial view (death to ASCX) read more
    You should NOT use ASP.NET MVC if. . . read more
    ASP.NET MVC Release Candidate read more
    MvcContrib latest release now with SubController support read more
    AJAX >> Using AJAX to load a usercontrol that has refers to a custom css file read more
    Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Performing Client Actions in Response to Partial Page Postbacks read more
    SharePoint Deployment Planning Services (SDPS) Released read more
    Digging into ASP.NET MVC - Part 1 read more
    Top
     
     
     

    Please login to rate or to leave a comment.