Steve Michelotti

C#, ASP.NET, and other stuff

  Home  |   Contact  |   Syndication    |   Login
  104 Posts | 1 Stories | 379 Comments | 51 Trackbacks

News

View Steve Michelotti's profile on LinkedIn






Google My Blog

What I'm Reading:

Shelfari: Book reviews on your book blog

Tag Cloud


Archives

Post Categories

Image Galleries

Blogs

Code

Publications

Saturday, November 07, 2009 #

In an effort to continually improve as a developer, one of the things I do is read lots of books. Recently I read ASP.NET MVC in Action by Jeffrey Palermo, Ben Scheirman, and Jimmy Bogard. In short, I consider this a “must read” for anyone who is serious about developing with the ASP.NET MVC framework.

I’ve heard some people say that this should not be your first MVC book because it is more advanced than other MVC books available.  While I can understand that logic to a degree, I think it would be more accurate to say that if you’re literally brand new to MVC, this might not be the best “introductory” book.  However, if I could only own one book on MVC, this book would be it. There are two common themes from this book that I really enjoyed. First, the authors base their content on “real world” concepts rather than just explaining every topic in a mechanical way. This gives a great real world context throughout the book.  Secondly, the authors are not afraid to be “opinionated” in their recommended best practices for the MVC framework. These are aspects that are lacking in many technical books.

The book starts out with a nice introduction to MVC (and it’s not too advanced to follow in the least). One of the things I really liked about this first chapter is that it spent some time discussing the history of web development which gave great context to where and how ASP.NET MVC fits into the discussion. This included many of the reasons as to *why* we have the MVC framework to begin with. The very next chapter dives into the Model of MVC and does a great job explaining the differences between domain models and presentation or view models.  Philosophically, I really agree with their concepts around view models and I have referenced some of them before on this blog. Understanding these view model concepts is essential to building mature MVC applications.

The books then dives into Controllers. The aspect I enjoyed most about this was the emphasis on unit testing. This included mocking and best practices for dependencies. The Controllers chapter ended with a discussion of action filters which was decent but I would have liked if the discussion of action filters had been expanded a little. The Views chapter provided great content covering validation, custom html helpers, partial views, and more. I didn’t find the Views chapter to be very advanced at all – rather, it provided a solid foundation for the type of information developers should know when building views.

I really appreciated the chapter on Routing. It discussed designing the routing topology of your application up front which is often overlooked. It also discussed REST best practices. The examples of Routing constraints were one of the strongest parts of the chapter and they are an area that I’ve observed is often overlooked in MVC applications. My favorite part of the Routing chapter was unit testing routes with the very cool route testing extensions available in the MvcContrib project which makes unit testing routes trivial. For example, it showed how you can test a route in one simple line of code like this: "~/boiseCodeCamp/edit".ShouldMapTo<ConferenceController>(x => x.Edit("boiseCodeCamp"));

Towards the end of the book there was a chapter dedicated to exploring (for the sake of contrasting and understanding historical context) MonoRail and Ruby of Rails.  I always find the comparisons between Ruby on Rails and MVC very interesting and that was true in this book as well.  However, I didn’t find myself as engaged in the MonoRail discussion and I didn’t think it added as much to the book as the Ruby on Rails section.

Probably the best chapter in the book was the one dedicated to Best Practices. Once again the authors were not afraid to be opinionated in their recommendations and this was based on “real world” experience with the framework (for which there is no substitute). One example I really liked from this section was the advocating of the RenderAction() method. This method has not been without its share of controversy because there are some “purists” that believe the existence of this method violates the tenets of the MVC framework because this means the view has some “knowledge” of the controllers. However, the authors point out (correctly, in my opinion) that the method allows for a much more elegant implementation in many cases that is a very pragmatic choice that actually leads to *better* separation of concerns in many instances since the partial gets its own controller.

Learning the mechanics of MVC is important. But even more important is learning best practices and how you can extend the MVC framework to suit your needs when the situation requires it. In my opinion, this is the best book I’ve read that can help get you to that goal.


Thanks to everyone who attended my “MVC in the Real World” presentation at CMAP Code Camp today.  The code as well as the PowerPoint can be downloaded here:

MVC in the Real World Download

I also had a few other requests during the talk.  First, I had a request to post the code as it looked at the very beginning of my talk before I modified anything.  You’ll find that link on the download page above as well (file name: PersonalInfoManager-ReadlWorldMVC-Begin.zip). 

Second, I was asked about a couple of the tools I was using.  You can see the links for all the tools I use (almost all free) on my Developer Tools and Utilities page.

Third, I had a request to post some links that discussed some of the Unit Testing best practices. Brad Wilson (one of the primary developers of xUnit) co-authored this excellent article: Effective Unit Testing. I also really like this slide deck which he also published: Lessons Learned in Programmer Testing. Roy Osherove also has a great post on Naming Standards for Unit Tests. Finally, I love this article by Jeremy Miller in MSDN magazine entitled Designing for Testability. One of his article’s major premises is that “testable” code typically will naturally result in “well designed” code – a concept that I’m a huge fan of.


Wednesday, November 04, 2009 #

Thanks to everyone who attended my C# 4.0 New Languages Features presentation at CMAP last night.  Both the code and PowerPoint are available for download.

C# 4.0 New Language Features Download

After the presentation, I had a few people ask me about some of tools I was using.  They can all be found on my Developer Tools and Utilities page. To create my snippets, I’ve been using a tool called Snippy for years (link included on Developer Tools page).  However, lately I’ve also been using Snippet Designer which is a Visual Studio add-in that is also quite good.


Sunday, November 01, 2009 #

I’ll be giving a presentation on C# 4.0 New Language Features this Tuesday at the CMAP Main Meeting.

Also I’ll be presenting MVC in the Real World this Saturday at CMAP Code Camp.

Hope to see you there!


Sunday, October 25, 2009 #

Since MVC has been released I have observed much confusion about how best to construct view models. Sometimes this confusion is not without good reason since there does not seem to be a ton of information out there on best practice recommendations.  Additionally, there is not a “one size fits all” solution that acts as the silver bullet. In this post, I’ll describe a few of the main patterns that have emerged and the pros/cons of each. It is important to note that many of these patterns have emerged from people solving real-world issues.

Another key point to recognize is that the question of how best to construct view models is *not* unique to the MVC framework.  The fact is that even in traditional ASP.NET web forms you have the same issues.  The difference is that historically developers haven’t always dealt with it directly in web forms – instead what often happens is that the code-behind files end up as monolithic dumping grounds for code that has no separation of concerns whatsoever and is wiring up view models, performing presentation logic, performing business logic, data access code, and who knows what else.  MVC at least facilitates the developer taking a closer look at how to more elegantly implement Separation of Concerns.

Pattern 1 – Domain model object used directly as the view model

Consider a domain model that looks like this:

   1:  public class Motorcycle
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:  }

When we pass this into the view, it of course allows us to write simple HTML helpers in the style of our choosing:

   1:  <%=Html.TextBox("Make") %>
   2:  <%=Html.TextBoxFor(m => m.Make) %>

And of course with default model binding we are able to pass that back to the controller when the form is posted:

   1:  public ActionResult Save(Motorcycle motorcycle)

While this first pattern is simple and clean and elegant, it breaks down fairly quickly for anything but the most trivial views. We are binding directly to our domain model in this instance – this often is not sufficient for fully displaying a view.

Pattern 2 – Dedicated view model that *contains* the domain model object

Staying with the Motorcycle example above, a much more real-world example is that our view needs more than just a Motorcycle object to display properly.  For example, the Make and Model will probably be populated from drop down lists. Therefore, a common pattern is to introduce a view model that acts as a container for all objects that our view requires in order to render properly:

   1:  public class MotorcycleViewModel
   2:  {
   3:      public Motorcycle Motorcycle { get; set; }
   4:      public SelectList MakeList { get; set; }
   5:      public SelectList ModelList { get; set; }
   6:  }

In this instance, the controller is typically responsible for making sure MotorcycleViewModel is correctly populated from the appropriate data in the repositories (e.g., getting the Motorcycle from the database, getting the collections of Makes/Models from the database).  Our Html Helpers change slightly because they refer to Motorcycle.Make rather than Make directly:

   1:  <%=Html.DropDownListFor(m => m.Motorcycle.Make, Model.MakeList) %>

When the form is posted, we are still able to have a strongly-typed Save() method:

   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]Motorcycle motorcycle)

Note that in this instance we had to use the Bind attribute designating “Motorcycle” as the prefix to the HTML elements we were interested in (i.e., the ones that made up the Motorcycle object).

This pattern is simple and elegant and appropriate in many situations. However, as views become more complicated, it also starts to break down since there is often an impedance mismatch between domain model objects and view model objects.

 

Pattern 3 – Dedicated view model that contains a custom view model entity

As views get more complicated it is often difficult to keep the domain model object in sync with concerns of the views.  In keeping with the example above, suppose we had requirements where we need to present the user a checkbox at the end of the screen if they want to add another motorcycle.  When the form is posted, the controller needs to make a determination based on this value to determine which view to show next. The last thing we want to do is to add this property to our domain model since this is strictly a presentation concern. Instead we can create a custom “view model entity” instead of passing the actual Motorcycle domain model object into the view. We’ll call it MotorcycleData:

   1:  public class MotorcycleData
   2:  {
   3:      public string Make { get; set; }
   4:      public string Model { get; set; }
   5:      public int Year { get; set; }
   6:      public string VIN { get; set; }
   7:      public bool AddAdditionalCycle { get; set; }
   8:  }

This pattern requires more work and it also requires a “mapping” translation layer to map back and forth between the Motorcycle and MotorcycleData objects but it is often well worth the effort as views get more complex.  This pattern is strongly advocated by the authors of MVC in Action (a book a highly recommend).  These ideas are further expanded in a post by Jimmy Bogard (one of the co-authors) in his post How we do MVC – View Models. I strongly recommended reading Bogard’s post (there are many interesting comments on that post as well). In it he discusses approaches to handling this pattern including using MVC Action filters and AutoMapper (I also recommend checking out AutoMapper).

Let’s continue to build out this pattern without the use of Action filters as an alternative. In real-world scenarios, these view models can get complex fast.  Not only do we need to map the data from Motorcycle to MotorcycleData, but we also might have numerous collections that need to be populated for dropdown lists, etc.  If we put all of this code in the controller, then the controller will quickly end up with a lot of code dedicated just to building the view model which is not desirable as we want to keep our controllers thin. Therefore, we can introduce a “builder” class that is concerned with building the view model.

   1:  public class MotorcycleViewModelBuilder
   2:  {
   3:      private IMotorcycleRepository motorcycleRepository;
   4:   
   5:      public MotorcycleViewModelBuilder(IMotorcycleRepository repository)
   6:      {
   7:          this.motorcycleRepository = repository;
   8:      }
   9:   
  10:      public MotorcycleViewModel Build()
  11:      {
  12:          // code here to fully build the view model 
  13:          // with methods in the repository
  14:      }
  15:  }

This allows our controller code to look something like this:

   1:  public ActionResult Edit(int id)
   2:  {
   3:      var viewModelBuilder = new MotorcycleViewModelBuilder(this.motorcycleRepository);
   4:      var motorcycleViewModel = viewModelBuilder.Build();
   5:      return this.View();
   6:  }

Our views can look pretty much the same as pattern #2 but now we have the comfort of knowing that we’re only passing in the data to the view that we need – no more, no less.  When the form is posted back, our controller’s Save() method can now look something like this:

   1:  public ActionResult Save([Bind(Prefix = "Motorcycle")]MotorcycleData motorcycleData)
   2:  {
   3:      var mapper = new MotorcycleMapper(motorcycleData);
   4:      Motorcycle motorcycle = mapper.Map();
   5:      this.motorcycleRepository.Save(motorcycle);
   6:      return this.RedirectToAction("Index");
   7:  }

Conceptually, this implementation is very similar to Bogard’s post but without the AutoMap attribute.  The AutoMap attribute allows us to keep some of this code out of the controller which can be quite nice.  One advantage to not using it is that the code inside the controller class is more obvious and explicit.  Additionally, our builder and mapper classes might need to build the objects from multiple sources and repositories. Internally in our mapper classes, you can still make great use of tools like AutoMapper.

In many complex real-world cases, some variation of pattern #3 is the best choice as it affords the most flexibility to the developer.

 

Considerations

How do you determine the best approach to take?  Here are some considerations to keep in mind:

Code Re-use – Certainly patterns #1 and #2 lend themselves best to code re-use as you are binding your views directly to your domain model objects. This leads to increased code brevity as mapping layers are not required. However, if your view concerns differ from your domain model (which they often will) options #1 and #2 begin to break down.

Impedance mismatch – Often there is an impedance mismatch between your domain model and the concerns of your view.  In these cases, option #3 gives the most flexibility.

Mapping Layer – If custom view entities are used as in option #3, you must ensure you establish a pattern for a mapping layer. Although this means more code that must be written, it gives the most flexibility and there are libraries available such as AutoMapper that make this easier to implement.

Validation – Although there are many ways to perform validation, one of the most common is to use libraries like Data Annotations. Although typical validations (e.g., required fields, etc.) will probably be the same between your domain models and your views, not all validation will always match.  Additionally, you may not always be in control of your domain models (e.g., in some enterprises the domain models are exposed via services that UI developers simply consume).  So there is a limit to how you can associate validations with those classes.  Yes, you can use a separate “meta data” class to designate validations but this duplicates some code similar to how a view model entity from option #3 would anyway. Therefore, option #3 gives you the absolute most control over UI validation.

 

Conclusion

The following has been a summary of several of the patterns that have emerged in dealing with view models. Although these have all been in the context of ASP.NET MVC, the problem with how best to deal with view models is also an issue with other frameworks like web forms as well. If you are able to bind directly to domain model in simple cases, that is the simplest and easiest solution. However, as your complexity grows, having distinct view models gives you the most overall flexibility.


Thursday, October 22, 2009 #

I ran into a small issue today when using the FluentHtml Select() HtmlHelper.  My original code was not properly setting the value of the selected item in the drop down:

<%=this.Select(m => m.Motorcycle.Make).Selected(Model.Motorcycle.Make).Label("Vehicle Make").Options(Model.MakeList)%>

I kept ending up with no item being selected from the drop down even though I definitely had a vehicle Make populated in my model and my drop down was correctly populated with the collection from the “MakeList” property of the view model.  It turns out that the solution was a simple matter of corrected ordering:

<%=this.Select(m => m.Motorcycle.Make).Options(Model.MakeList).Selected(Model.Motorcycle.Make).Label("Vehicle Make")%>

In hindsight I guess this order makes a little more sense intuitively anyway.  However, the fluent API did not constrain me from running into this issue.  So, just a heads up, when using the Select() helper, set the Options() first, and then set the selected value by invoking the Selected() helper method.


Wednesday, October 14, 2009 #

I ran into an interesting IoC issue today that was ultimately resolved by some extremely helpful email assistance by Chad Myers. I’ll post the solution here in the hopes that someone else will find it helpful. Here is the code to set up the example:

   1:  public interface IFoo
   2:  {
   3:      IBar Bar { get; set; }
   4:  }
   5:   
   6:  public class Foo : IFoo
   7:  {
   8:      public IBar Bar { get; set; }
   9:   
  10:      public Foo(IBar bar)
  11:      {
  12:          this.Bar = bar;
  13:      }
  14:  }
  15:   
  16:  public interface IBar
  17:  {
  18:      bool Flag { get; set; }
  19:  }
  20:   
  21:  public class Bar : IBar
  22:  {
  23:      public bool Flag { get; set; }
  24:   
  25:      public Bar(bool flag)
  26:      {
  27:          this.Flag = flag;
  28:      }
  29:  }

The key here is that Bar has a constructor that takes a Boolean parameter and there are some circumstances where I want Bar to have a true parameters and some instances where I want it to be false.  Because of this variability, I can’t just initialize like this:

   1:  x.ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar>().WithCtorArg("flag").EqualTo(true);

That won’t work because that only supports the “true” parameter for IBar. In order to support both, I need to utilize named instances.  Therefore, my complete StructureMapBootstrapper looks like this:

   1:  public static class StructureMapBootstrapper
   2:  {
   3:      public static void Initialize()
   4:      {
   5:          ObjectFactory.Initialize(x =>
   6:              {
   7:                  x.ForRequestedType<IFoo>().TheDefaultIsConcreteType<Foo>();
   8:                  x.ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar>().WithCtorArg("flag").EqualTo(true).WithName("TrueBar");
   9:                  x.ForRequestedType<IBar>().TheDefault.Is.OfConcreteType<Bar>().WithCtorArg("flag").EqualTo(false).WithName("FalseBar");
  10:              });
  11:      }
  12:  }

This now enables me to create instances of IBar by using the GetNamedInstance() method.  However, the primary issue is that I need to create an instance of IFoo and Foo has a nested dependency on IBar (where the parameter can vary).  It turns out the missing piece to the puzzle is to simply leverage the ObjectFactory’s With() method (in conjunction with the GetNamedInstance() method) which takes an object instance and returns an ExplicitArgsExpression to enable the fluent syntax. Therefore, these instances can easily be instantiated either way like this:

   1:  var fooWithTrueBar = ObjectFactory.With(ObjectFactory.GetNamedInstance<IBar>("TrueBar")).GetInstance<IFoo>();
   2:  var fooWithFalseBar = ObjectFactory.With(ObjectFactory.GetNamedInstance<IBar>("FalseBar")).GetInstance<IFoo>();

Just another example of how IoC containers can enable us to keep clean separation of concerns in our classes and enable us to avoid cluttering our code with the wiring up of dependencies.


I often get asked what IoC Container I prefer.  Short answer: StructureMap. I love the fluent syntax for configuration. Overall, it’s easy to use, has many advanced features, and is very lightweight.  I view the learning curve with StructureMap as relatively small.  It is one of the longest-lived IoC containers (if not *the* longest) and has a huge adoption rate which means it’s quite mature and not difficult to find code examples online. For example, there is the StructureMap mailing list. Additionally, the community is very proactive – I just sent an email question to Chad Myers today and got a response within minutes that solved my issue. The creator of StructureMap, Jeremy Miller, has one of the most useful blogs around (in addition to his column in MSDN magazine).

Despite all this, there are still several other very high quality IoC containers available including: Unity, Ninject, Windsor, Spring.NET, and AutoFac. Unity is Microsoft’s offering in the IoC space and often it gets picked simply because it’s got the “magical” Microsoft label on it.  In fact, some organizations (for better or worse – usually worse) have policies *against* using OSS software and your only choice is to look at the offerings on the Microsoft platform.  Despite this, Unity is actually pretty good but by P&P’s own admission, there are instances where StuctureMap implementation is a little more elegant than Unity. But Unity does still have some compelling reasons to use it. In fact, if you are already using the Microsoft Enterprise Library Application Blocks, choosing Unity makes sense for a little more seamless experience.

Having said all this, there is one other major caveat to my preference towards StructureMap – it’s the IoC tool I’m most familiar with. Therefore you should take a recommendation from me (or *anyone*) with a grain of salt.  Ultimately the features of the various IoC’s are going to be comparable and it’s the developer familiarity with that tool that is going to make the difference.  For folks new to IoC, most of the uses are going to be for simple constructor dependency injection and all the IoC frameworks can handle that easily.  Given the wealth of quality IoC frameworks, we need another IoC framework about as bad as we need another data access technology. :)


Saturday, October 10, 2009 #

Thanks to everyone who attended my session today at NoVa Code Camp.  Both the code and PowerPoint slides are available for download.

Download samples for: MVC in the Real World. Check out the readme.txt file in Solution Items and all SQL scripts for creating the databases.


Wednesday, October 07, 2009 #

This Saturday (October 10) I’ll be presenting at the NoVa Code CampRegistration is still open.

I will be presenting “MVC in the Real World”.  There are many great sessions on the schedule.  Hope to see you there!


Sunday, October 04, 2009 #

Thanks to everyone who attended my sessions yesterday at Richmond Code Camp.  Both the code and PowerPoint slides are available for download.

Download samples for: MVC in the Real World. Check out the readme.txt file in Solution Items and all SQL scripts for creating the databases.

Download samples for: C# 4.0 New Language Features.

I had several questions about some of the tools I was using during the presentations (all of which are free).  For the zooming and highlighting, I was using a tool called ZoomIt. For the code snippets, I was just utilizing the built-in code snippets functionality of Visual Studio – however, I use a tool called Snippy to create all of my custom snippets. You can find links to those tools and many other tools I use on my Developer Tools and Utilities post.


Thursday, October 01, 2009 #

MVP

I just found out today that I was awarded the MVP designation from Microsoft in the area of ASP.NET. It has been a very busy 2009 for me, speaking at various user groups and code camps including CMAP, CapArea, RockNUG, SoMDNUG, FredNUG, and Richmond Code Camp.  I would like to thank all of those user groups for having me present and I look forward to continuing my involvement with all of those user groups and more in the year to come.

With .NET 4.0 and the 2010 wave just around the corner, the upcoming year looks to bring some exciting enhancements in numerous areas including MVC, WCF REST, C# 4.0, Dublin, and the .NET framework in general.


Monday, September 28, 2009 #

This Saturday (October 3) I’ll be presenting at Richmond Code CampRegistration is still open. 

I will be presenting “MVC in the Real World” – Move beyond MVC 101 and dive into aspects of building robust, real-world MVC applications. This demo-heavy presentation will show how to fully unit test the presentation layer with mocking and Dependency Injection.  This session will show the benefits of using Inversion of Control (IoC) containers to create controllers with a custom controller factory. In addition to AJAX-enabling Views, we will explore how to build your own custom HTML helpers that can be reused across Views. By the end of the session we will cover Action filters, security, T4 templates, MvcContrib, FluentHtml, and more!

Hope to see you there.


Tuesday, September 01, 2009 #

In a previous post, I showed how to submit an AJAX form in MVC with the jQuery Thickbox and the built-in MVC AJAX helpers.  If you read that post first, it will show the complete context for how to simply submit an AJAX form that is being rendered inside a jQuery Thickbox with built-in MVC AJAX helpers.  But what if you want to stick to a pure jQuery solution?  That is also simple enough to do.  Instead of using the Ajax.BeginForm() method, you can use the jQuery Form Plugin.  The code is almost identical to the previous implementation.  The only differences are in the Index.ascx partial view:

   1:  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcAjaxForm.Models.ContactMessage>" %>
   2:   
   3:  <script type="text/javascript">
   4:      $(function() {
   5:          $("#contactForm").ajaxForm({ target: '#contactArea' });
   6:      });
   7:  </script>
   8:   
   9:  <h2>Contact</h2>
  10:      
  11:  <form id="contactForm" action="<%=Url.Action("Index", "Contact") %>" method="post">
  12:      <div id="contactArea">
  13:          Email Address: <%=Html.TextBox("EmailAddress") %> <br /><br />
  14:          Message: <%=Html.TextArea("MessageText")%>
  15:          <input type="submit" />
  16:      </div>
  17:  </form>

On line 11, you will now specify a normal HTML form just like you might specify any other form in MVC (you could also use the Html.BeginForm() method as well if you have that preference). The only additional thing you have to implement is the one line of code shown on line 5 above.  This is making a call to the ajaxForm() method (that comes in the Form Plugin library) and passes in the options to indicate that the response from the server should be displayed in the “contactArea” div.  This is just one example of how to use the Form plugin – you can also find numerous example within the Form Plugin’s documentation site.


Monday, August 31, 2009 #

A relatively common scenario you might want in your application is the ability for a user to click a link that pops up a little dialog to submit some information.  For example, let’s say you have this form where the user could click the “Contact this person” link:

 

After clicking this link, it pops up the following dialog where the user can type in their message:

 

Finally, once the user submits their message, it shows a little confirmation:

 

This scenario can be implemented with MVC with very few lines of code.  First off, we’ll be using the AJAX HTML Message pattern so that the AJAX messages that are going across the wire are simple HTML snippets.  Also, we’ll use jQuery Thickbox for our dialog. The first thing we need to do it to implement our “Contact this person” link:

   1:  <%=Html.ActionLink("Contact this person", "Index", "Contact", new { height = 200, width = 300 }, new { @class = "thickbox" }) %>

This is a pretty typical implementation of the jQuery thickbox.  We’re specifying that we want an AJAX call to be made to our ContactController.Index() method. The HTML that this ActionLink renders will simply look like this:

   1:  <a class="thickbox" href="/Contact?height=200&amp;width=300">Contact this person</a>

The complete code for the ContractController looks like this:

   1:  public class ContactController : Controller
   2:  {
   3:      public ActionResult Index()
   4:      {
   5:          return View(new ContactMessage());
   6:      }
   7:   
   8:      [ActionName("Index")]
   9:      [AcceptVerbs(HttpVerbs.Post)]
  10:      public ActionResult SubmitMessage(ContactMessage message)
  11:      {
  12:          return this.View("Confirmation", message);
  13:      }
  14:  }

It is important to note that both views returned by the ContactController’s action methods are both partial views (i.e., Index.ascx and Confirmation.ascx) with our HTML snippets in there. We know that in the Index.ascx we want to do an AJAX form submission/post rather than a full page form submission. There are a couple of ways to do this including using the jQuery Form plugin. However, in this case, the MVC framework already comes built-in with this functionality so we don’t have to rely on the jQuery Form plugin (unless we want to). Most of the time we find ourselves using the Html property of the View which is of type HtmlHelper.  However, there is also an Ajax property of the view of type AjaxHelper. The AjaxHelper has a BeginForm method that will allow you to submit the form via AJAX. You’ll need to make sure you include the MicrosoftAjax.js and MicrosoftMvcAjax.js scripts in your page to use the Ajax helpers.  The complete implementation for the Index.ascx can just look like this:

   1:  <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcAjaxForm.Models.ContactMessage>" %>
   2:   
   3:  <h2>Contact</h2>
   4:      
   5:  <% using (Ajax.BeginForm("Index", "Contact", new AjaxOptions { UpdateTargetId = "contactArea" } )) { %>
   6:      <div id="contactArea">
   7:          Email Address: <%=Html.TextBox("EmailAddress") %> <br /><br />
   8:          Message: <%=Html.TextArea("MessageText")%>
   9:          <input type="submit" />
  10:      </div>
  11:  <% } %>

Notice the UpdateTargetId is specifying the “contactArea” div.  This causes all HTML that is sent back on the form post (i.e., the confirmation message) to be displayed inside this div only.  The complete code for this sample can be downloaded here.