Published: 22 Apr 2010
By: Brian Mains

Brian Mains explains how to use multiple actions in ASP.NET MVC 2.0.

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

    In the previous article, we saw a basic implementation of constructing the user interface. But in the real world, we need a more complex approach to developing the UI. Users don't want to navigate through an application by clicking multiple links to get the information they want; they want to be able to have all of the information in one view at their fingertips.

    In ASP.NET MVC, we still have user controls to create reusable components in an application, which are called partial views. This has been an approach since ASP.NET MVC 1.0, and we'll be using this approach here, in combination with a new feature with MVC 2.0: using the Html.Action option.

    Setting up the UI

    In web forms, when the UI becomes complex, developers either deal with the complexity that has formed into one humongous ASPX page or break the logic out into separate user controls or custom controls. Typically, custom controls are only used when the ultimate level of reuse is needed, and user controls are leveraged because of their ease of use and designer capabilities. In MVC, I mentioned that these features are still available using partial views (the equivalent of user controls) or custom HTML helpers (the equivalent of custom controls).

    A new feature, using the Html.Action method, allows an action method to inject its response directly into a parent view. The second action method returns a partial view to inject, and can be implemented as a self contained entity or sorts; the partial view can setup a form to post back to its controller while the main view can post back to a different controller. It's pretty neat how forms can interact, but there are implementation concerns with this approach. Let's take a look at a sample of this.

    Listing 1: Sample Form With Html.Action

    Here we have a simple form. This form contains two fields, followed by a call to an action method called custom within the same controller. The Action helper method takes the action to invoke, controller name (optional), and any data to pass to the controller method itself in the form of routing values. Listing 2 represents the partial view that becomes injected and part of the main view. This view defines its own form (a way to keep the partial self-contained). Any post backs to the server get redirected to this Custom action method, rather than to the main action method. This is an important point.

    Listing 2: Injected Partial View

    The partial view is self contained and is agnostic about the parent view, except for the information of the request (it uses all of the same sources of data (such as the HTTP context and routing data) available to the parent view. Now, we have a form that looks like the following in the browser.

    Figure 1: Setup Form

    Setup Form

    The MainAction section is the UI created from the parent view, while the Custom Action is setup as the partial view. The controller to process the form posts is shown in Listing 3.

    Listing 3: Controller

    You may wonder how this works exactly; after all, we have two distinct processes working here: the main form's content and the child's content. There isn't any inherent concept of ViewState in MVC, so posting back the child view will not automatically retain the parent view's data, which is very important to understand. When the submit button is clicked for the child controller method, it posts back its content, without posting back the parent view's content. So the dilemma here is to plan a good strategy for handling this scenario.

    Before we get into that, let's take a look at what the underlying markup looks like to post the content back to the action method. Below is our sample markup of the two forms, notice the form action methods, and control references.

    Listing 4: HTML markup

    We have two distinct forms (a change from how web forms works, as it has one form wrapping all controls) that postback independently, or possibly more.

    Using AJAX

    The previous approach could result in a lot of extra work for your controller. The injected partial view performs a postback to the Custom action method, which in turn does the post processing, and redirects back to the original view to display the new data. This is a lot of work, and using AJAX can save some time and processing. Listing 5 replaces the partial view in Listing 2 to post the form data asynchronously.

    Listing 5: Using the AJAX form

    Note the UpdateTargetID property; this property designates an HTML element target to inject a response into. The update target is the target for the action result of the calling method when posting in AJAX mode. The form posts to the server within the form's elements, and is handled in Listing 6. Note some extra care.

    Listing 6: Returning a Response

    When working with multiple actions in a view, the form needs to worry about whether the request is being made synchronously or asynchronously. If the request is an AJAX request, the content of the result will be injected into the update target, a DIV. We don't want to return the partial view because that would duplicate the UI into our custom response DIV (the update target). Alternatively, we don't need to use the update target to reload the existing UI because the UI never goes away in an AJAX request.

    On the other hand, synchronous requests when AJAX isn't working post back to the server and require you to handle the entire request. Returning just the content for the success message wouldn't work as expected, because the UI would then be gone. When the request posts back without AJAX, you have to handle the entire request, you are given full control. This means that you have to return the entire partial view UI on every synchronous request, and be aware of when this situation may happen. Handling both scenarios can be considered following the technique of unobtrusive JavaScript, where the application can run with or without JavaScriptor AJAX.

    In this example, the scenario happened because the main view submit button does not submit its content using an AJAX form, and thus fired a full post to the server. Since MVC gives us full control over what gets rendered for each and every request, we have to be responsible for returning the same UI with the information.

    Using JQuery

    JQuery works very well with MVC. JQuery adds the ability to get and post data to the server using AJAX, and very simply too. ASP.NET MVC detects an AJAX request in the same way as it would with the ASP.NET MVC client-side components, and thus the integration is seamless. Take a look at a sample form below.

    Listing 7: Setting up HTML.Action with JQuery

    Note the extra step of wrapping the partial view (returned from JQueryCustomIndex) within a DIV; this makes it a little easier to target a region for updating.

    There are a few concerns when using JQuery; first, you have to ensure you replace the entire content of the updated section, so everything within our custom DIV must be wiped out and replaced. Secondly, JavaScript doesn't get executed in the partial view when an AJAX replacement occurs; this means that the script must reside in the view, and the view has to know about the partial to update (which means the view is coupled to the partial view, unless you do some added work to prevent this). Listing 8 has the script to do the update.

    Listing 8: Updating the Partial View

    JQuery, on load, attaches to the first form within our DIV target. When it submits, the default execution of the submit is cancelled, and JQuery performs the post. The post replaces our target DIV with the new DIV and its content. When replacing elements, we lost our submit handler, and the process needs to reattach (though I probably could have used another event handling approach in JQuery like the live method to remedy the reattachment issue).

    So the partial view submits the data, JQuery blocks the form submit, performs the post to the server, replaces the HTML content with the new content from the controller action method, and swaps the elements out, while making it seamless to the user.

    Conclusion

    ASP.NET MVC 2 adds an Html.Action method to allow multiple action methods to work within one view, which is a really powerful addition. You have to be careful how the form posts to the server with multiple forms, which can be an issue for developers to manage. AJAX remedies this, whether the in-built MS AJAX or JQuery.

    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


    Understanding the MvcRouteHandler and MvcHandler in ASP.NET MVC read more
    Html Encoding Nuggets With ASP.NET MVC 2 read more
    ASP.NET MVC2 Preview 2: Areas and Routes read more
    MvcContrib working on Portable Areas read more
    Video: DevExpress Plans For ASP.NET MVC read more
    MvcContrib version control has moved to GitHub read more
    Lots of buzz about MvcContrib! read more
    The ASP.NET MVC ActionController The controllerless action, or actionless controller read more
    Going Controller-less in MVC: The Way Fowler Meant It To Be read more
    Afternoon of ASP.NET MVC [16 June] (free Headspring event) read more
    Top
     
     
     

    Discussion


    Subject Author Date
    placeholder Brilliant article Nik D 5/6/2010 11:05 PM

    Please login to rate or to leave a comment.