A simple example of a asynchronous ASP.NET MVC 4 action methods
With this knowledge of how to use asynchronous methods, I'll go back to ASP.NET MVC 4. I'll have the previously created MathService class use asynchronous execution in an ASP.NET MVC 4 app with a Razor view. To keep things simple, the sample solution has a simple structure and I don't create an additional project for the service. So, forgive me for using the MathService class without dependency injection. Don't consider direct instantiation the best-practice for ASP.NET MVC 4. Figure 5 shows the detailed structure for the Mvc4AsyncAwaitSample solution:
- Controllers
- MathController.cs
- Models
- Math
- DetailsModel.cs
- Views
- Math
- TotalSummary.cshtml
- MathService.cs

Figure 5. The Mvc4AsyncAwaitSample solution with an ASP.NET MVC 4 example that uses asynchronous methods.
Here, I want to use two methods that were declared private in my previous example. The following lines show the two methods that are now public in the MathService class:
public static async Task<decimal> GetSubTotalAsync()
{
var downloadedString =
await new WebClient().DownloadStringTaskAsync(new Uri("http://www.drdobbs.com"));
return (decimal)downloadedString[0];
}
public static async Task<decimal> GetOtherChargesAsync()
{
var downloadedString =
await new WebClient().DownloadStringTaskAsync(new Uri("http://www.drdobbs.com"));
return (decimal)downloadedString[1];
}
I've included DetailsModel in the Mvc4AsyncAwaitSample.Models.Math namespace. The following listing shows the code for DetailsModel.cs with just two properties:
namespace Mvc4AsyncAwaitSample.Models.Math
{
public class DetailsModel
{
public decimal SubTotal { get; set; }
public decimal OtherCharges { get; set; }
}
}
The following code shows the code for the TotalSummary.cshtml view that uses the Razor engine. The view just displays the values for SubTotal and OtherCharges:
@model Mvc4AsyncAwaitSample.Models.Math.DetailsModel
@{
ViewBag.Title = "Total Summary (Async Sample)";
}
<h3>Total Summary</h3>
<fieldset>
<legend>Total Summary</legend>
<div class="display-label">
@Html.DisplayNameFor(model => model.SubTotal)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.SubTotal)
</div>
<div class="display-label">
@Html.DisplayNameFor(model => model.OtherCharges)
</div>
<div class="display-field">
@Html.DisplayFor(model => model.OtherCharges)
</div>
</fieldset>



