How To Load Partial Views In ASP.NET MVC Using jQuery Ajax

In this article, we'll discuss partial views in ASP.NET MVC and loading them via jQuery AJAX. There could be several scenarios for this. Let's assume that we have a page that contains multiple partial views and data from various sources. So we can load each partial view using AJAX individually, it will improve the user experience because the components that can be loaded earlier won't be delayed until all the components load. As soon as each control loads, they will be available to the user on the screen.

I have used ASP.NET MVC3 for this article but it does not matter whether you use MVC3 or MVC4 or MVC5. I have created a main View (called here HomePage.cshtml) and created two Partial Views (_ProductDetails.cstml and _UserDetails.cshtml) that will be displayed. So I'll show you how easily we can load these controls viaAjax. It will make the page more intuitive and seamless to users.
I am showing simple data in these controls and and one control display the details of the users and other control displays product details. For this, I have created two models, User and Product.

Also I have created two methods GetUserDetails and GetProductDetails in Home Controller. GetUserDetails returns a list of users and GetProductDetails returns a list of products.

While we can load each control easily via jQuery AJAX. For this jQuery must be included in the on the View. By default it is included in the __Layout.cshtml. It works as a master layout of the page but if you are not using it in your View then include the jQuery file specifically. So my HomePage.cshtml looks like:

homepage.png

Client-side code is as:

JavascriptCode.png

So here you can see each control is loaded individually. For each control, I have defined a method in Controller and that method is called via Ajax . When the result is returned from the ajax call successfully then that success event is fired. Here I am setting the returned HTML in a div and displaying it.

Also here we can easily pass the parameter to the controller methods if we want, via URL itself. Two partial Views are,

Product partial view ( _ProductDetails.cshtml) is as,

Productpng.png

And the user partial view ( _UserDetails.cshtml) is as,

users.png

Now when the page loads it fires two ajax calls fired individually and when the result is returned then the control is displayed. In the meantime, the user may see a blank screen, so here we can show some loader image and once the result is returned and we hide it we display the control in a success event.

When we'll run the application, it looks like,

afterrunning.png

These controls load individually via AJAX.

Next Recommended Readings