Please enable Javascript for better experience...
Improving application performance using Asynchronous call in MVC
By Big | Nov 25, 2014 | In Articles | Update: Nov 26, 2014 | Total Views [ 6088 ]
Taged In
(4 Like)
Rate

Performance issue is a big hole for any application now a day and if we talk in terms of a MVC application then this is clearly unacceptable. In this article I will explain how to overcome performance issue using Asynchronous calls.

Introduction

Though MVC applications are well known for its light weight and fast execution but still it can face performance issues if not implemented in a proper way. Some time it may also happen due to heavy data flow in application. There are so many ways by which performance can be speed up like improving database structure, adding indexes to it, optimizing queries or through code optimization, improving business logics and action rendering. But there can be few cases when slowness exists even appying all these known tricks. In such case we can apply asynchronous rendering of partial views. In this article I will try to explain this technique with a simple example.

Using the Code

Before going next we should first understand what exactly Asynchronous means and how can it help in improving performance of your MVC application.

Asynchronous Meaning

In general Asynchronous means that a process operates independently of other processes. Whenever we make an Asynchronous Call, it is totally independent to other processes being called at the same time.

We can use two ways of calling a process-Synchronous and Asynchronous. Unlike Asynchronous, synchronous is a process which runs only as a result of some other process being completed.

From above discussion, it is little bit clear that why applying async call, performance speeds up. Now let's move step by step to understand it better.

Normal approach

Let's create a simple MVC application for online shopping with one view and two partials views. Below is the code for the same. These code are just for demo purpose and not are the actual code but you can write your own logic using same approach I am showing.

Model

Let's create a model and name it as OnlineShoppingModel. Below is the code.

 public class OnlineShoppingModel
    {
        public NewOrder NewOrder { get; set; }
        public StockList StockList { get; set; }
        public OrderList OrderList { get; set; }
    }
    public class NewOrder
    {
        //put your code
    }
    public class StockList
    {
        //put your code
    }
    public class OrderList
    {
        //put your code
    }

Controller

After model, let's create a controller and add some logic to it. I am naming it as OnlineShoppingController. You can create only one method in controller to fetch all the related details and return to a view where all the partials can be render through Html.RenderPartial() method but I am creating three separate methods and will call them accordingly. I am also doing this because of its future use in example that I will discuss in some time. Below is the code for my controller.

Business Logic

public class OnlineShoppingBL
    {
        public StockList GetStockList()
        {
            //put your code
            return new StockList();
        }
        public OrderList GetOrderList()
        {
            //put your code
            return new OrderList();
        }
    }

Controller

    public class OnlineShoppingController:Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult StockList()
        {
            OnlineShoppingModel model = new OnlineShoppingModel();
            model.StockList = new OnlineShoppingBL().GetStockList();
            return PartialView("_StockList",model);
        }
        public ActionResult OrderList()
        {
            OnlineShoppingModel model = new OnlineShoppingModel();
            model.OrderList = new OnlineShoppingBL().GetOrderList();
            return PartialView("_OrderList", model);
        }
    }

View

After controller now it is time to create a view to show data. Below is the view I created. In this example I have created One view and two partial views. I will discuss its use later. Here I am using Html.RanderAction() helper method to render partials. If instead of three methods which I created in controller, I would created only one method as I said earlier then I would use Html.RenderPartial() method for loading these partials. Let see the view.

@{
        Html.RenderPartial("_NewOrder");
        Html.RenderAction("StockList");
        Html.RenderAction("OrderList");
    }

Asynchronous approach

Above approach will take some time to load as all partials will load one by one. And time will be more if heavy data is coming. Let's see same example with async call. Here Model and Controller will be same because in controller I already created separate methods to render each partial views separately. So we need not to touch them. The only change I will make, is in view and side by side I will add few lines of code of javascript to perform async call. So let see view changes first.

View

To make async call I am doing few changes in view. Here I am binding New Order partial view directly with Html.RenderPartial() method and taking two div tag with loading image inside and adding data attribute to hold action name to call them asynchronously. Let's see the changes I made.

  @{
        Html.RenderPartial("_NewOrder");
        <div class="loader" data-action="/OnlineShopping/StockList">
            <img src="~/Content/Images/loading.gif" />
        </div>
        <div class="loader" data-action="/OnlineShopping/OrderList">
            <img src="~/Content/Images/loading.gif" />
        </div>
    }

Script

After adding view, now I can add code to call partials(StockList and OrderList) asynchronously. Here I can use two approach. Either I can use $ajax() or I can use load() method. Below is the code.

Using $ajax() method

<script language="javascript">
        $.ajax({
            url: "/OnlineShopping/StockList",
            success: function (result) {
                $(".loader").html(result);
            }
        });
$.ajax({
            url: "/OnlineShopping/OrderList",
            success: function (result) {
                $(".loader").html(result);
            }
        });
    </script>

Using load() method

load() method is the simple but powerful method of AJAX which loads data from server and bind the content to the selected element.

<script language="javascript">
        $(".loader").each(function (index, ctrl) {
            var url = $(ctrl).data("action");
            if (url && url.length > 0) {
                $(ctrl).load(url);
            }
        });
    </script>

Hope it can help you. Please try this and use in your code. It can be really helpful in speeding up your application.

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment