There are several ways to bind partial views and display them on views. But what is the best way? When I was working on one of my projects, I was concerned about which techniques I would need to use to make my website faster, and also if we are binding multiple partial views on the same page,  which are getting the data from the database. So, those things are very complicated and in this scenario we need to choose the way which will load every partial view independently. 

So, today I will discuss that. Whenever we talk about the partial view data to bind with it, we find several ways to bind the partial view. The following are a few examples.

We can bind some static data with partial view as following

@Html.Partial("SideBar")

We can also direct bind the partial view with Model.

@Html.Partial("RecentPost", Model.RecentPostl)

Partial view can be bind with ViewBag as well.

@Html.Partial("_MyPartial", (double)@ViewBag.piValue)


Now I am going to show different ways to bind the partial views. 

First Way [Bad Way, Don’t Use]

I have seen many developers bind all the partial views on a single request. Actually they try to get all the partial views data as entity on action result and return view with model data. As inthe  following example, you can see that I need Recent Post and Popular Post.

public class SideBarPostViewModel  
{  
    public List < RecentPost > RecentPost  
    {  
        get;  
        set;  
    };  
    public List < PopularPost > PopularPost  
    {  
        get;  
        set;  
    };  
}  

But on the controller, I have used only one Action Result for getting the data for both partial views.

public ActionResult GetAllPost()  
{  
    var model = new SideBarPostViewModel();  
    model.RecentPost = _db.getRecentPostList();  
    model.PopularPost = _db.getPopularPostList();  
  
    return View(model);  
} 

  

You can see clearly i the following code that on the single view I am passing the multiple partial view which data is coming from a single request.

@model AspNetDemo.ViewModels.SideBarPostViewModel  

 

Here you can pass some other view data,

@Html.RenderPartial("RecentPostPartialView", model.RecentPost);  
  
@Html.RenderPartial("PopularPostPartialView", model.PopularPost);  

So, as per concern of performance, this is a bad way to bind the partial view.

Second Way [So-So Good]

We can also return the partial view fromthe  action result. So, basically in this scenario we return a partial view as a div.

@{ 
   Html.RenderAction("GetMyAddress", "User");  
}  

and on controller:

[ChildActionOnly]  
public PartialViewResult GetMyAddress()  
{  
    return PartialView("_myAddress");  
}

 

So, we can see that with above syntax that PartialViewResult is returning a partial view from controller. This will be good if you are binding only single partial view. But if you have multiple partial views for single view then it will not good way to bind.

Third Way [Best Way, Always Use]

As per my knowledge the best way is to bind multiple partial views on one view to use ajax call and render all the partial view separately. Every partial view will make their own request for getting the data from database and bind with partial view. 

If we process the separate request for the individual partial view then it will not affect the performance of the site. It is because this will not affect loading  the page. The page will be load and partial view will be trying to get the data asynchronously.

On the following example, I am going to show how to create multiple partial view and make separate request for getting the data from database. Basically I am getting Recent Post and Popular Post on the view,

View with Partial Views

<div>  
    <div class="panel panel-default text-left">  
        <div class="panelheaderRed">  
            Recent Articles  
        </div>  
        <div class="panel-body">  
            <div id="dvHomeRecentPostBind">  
                <div class="loaderCenter">  
                    <span class="loadingText">Recent Articles Loading....</span>  
                </div>  
            </div>  
        </div>  
    </div>  
</div>  
<div>  
    <div class="panel panel-default text-left">  
        <div class="panelheaderGreen">  
            Popular Articles  
        </div>  
        <div class="panel-body">  
            <div id="dvHomePopularPostBind">  
                <div class="loaderCenter">  
                    <span class="loadingText">Popular Articles Loading....</span>  
                </div>  
            </div>  
        </div>  
    </div>  
</div> 

My Controller

public class RecentsController: BaseController  
{  
  
    private readonly IPostRepository _postRepository;  
    private readonly ICategoryRepository _categoryRepository;  
  
    public RecentsController(IPostRepository postRepository, ICategoryRepository categoryRepository)  
        {  
            _postRepository = postRepository;  
            _categoryRepository = categoryRepository;  
        }  
        //  
        // GET: /Recents/  
  
    [HttpGet]  
    public ActionResult RecentPosts()  
    {  
        var postEntity = _postRepository.GetPosts().OrderByDescending(x => x.PostUpdatedDate).Take(5).Select(x => new PostViewModel()   
        {  
  
            PostTitle = x.PostTitle,  
                PostAddedDate = x.PostAddedDate,  
                PostUrl = x.PostUrl,  
                postCategory = _categoryRepository.GetSingleCategoryInfo(x.CategoryId)  
        });  
  
        return PartialView("RecentPosts", postEntity);  
    }  
  
    [HttpGet]  
    public ActionResult PopularPosts()  
    {  
        var postEntity = _postRepository.GetPosts().OrderByDescending(x => x.NumberOfViews).Take(5).Select(x => new PostViewModel()  
           a{  
            PostTitle = x.PostTitle,  
                PostAddedDate = x.PostAddedDate,  
                PostUrl = x.PostUrl,  
                postCategory = _categoryRepository.GetSingleCategoryInfo(x.CategoryId),  
                NumberOfViews = x.NumberOfViews  
  
        });  
  
        return PartialView("PopularPosts", postEntity);  
    }  
  
}  

Jquery [Ajax Call]

function LoadHomeRecentPost()  
{  
    $.ajax  
    ({  
        url: "/Recents/RecentPosts",  
        contentType: "application/html; charset=utf-8",  
        type: "GET",  
        cache: !0,  
        datatype: "html",  
        success: function(t)  
        {  
            $("#dvHomeRecentPostBind").html(t)  
        },  
        error: function()  
        {  
            $("#dvHomeRecentPostBind").html("Post Not Found")  
        }  
    })  
}  
  
function LoadHomePopularPost()  
{  
    $.ajax  
    ({  
        url: "/Recents/PopularPosts",  
        contentType: "application/html; charset=utf-8",  
        type: "GET",  
        cache: !0,  
        datatype: "html",  
        success: function(t)  
        {  
            $("#dvHomePopularPostBind").html(t)  
        },  
        error: function()  
        {  
            $("#dvHomePopularPostBind").html("Post Not Found")  
        }  
    })  
}  
  
$(document).ready(function()  
{  
    LoadHomeRecentPost(), LoadHomePopularPost()  
}); 

When you run the website, you can see clearly in the following image that the  website has been loaded but the content is still loading so, herethe website is not waiting for loading all the content of the site.

Partial View

The part which is going to load, you can show the loading content message, if the request will get the response from the server than the data will be bound with partial view. So, using this you can make your asp.net mvc website faster. When your site will load properly then it will look like the following image with whole data.

Partial View Loading
 

Thanks for reading this article, hope you enjoyed it.