Tuesday, May 28, 2013

Load MVC3 Partial View using jQuery

In one of my project I had requirement where partial view was supposed to be loaded using jQuery. This is very common requirement for interactive UI. We may have requirement where we need to load partial views based on timer (refresh the sections on UI).

To accomplish this task I wrote a method which renders the partial view in stream and then send it as JSONResult to UI.

There are 2 ways to render partial views:

1. Using ActionResult and jQuery.get
2. Using JSONResult and return partial view html along with some other custom data from server.

I am using mvc 3 application to demonstrate this. There will be a button on page which will get the partial view from controller and renders that into a div. Index is the default view to load.











Below is the folder structure of project:



















Index view html:


















Partial View html:



The desired result is:










I will demonstrate both ways. Lets have a look at the first one:

1. Using ActionResult and jQuery.get

 Index view:

This view contains button to load the partial view. We are binding onClick event of button to load partial view using $.get.






 HomeController.cs:











Code block return PartialView("Employee", employees); returns partialview html and .done(result) block on Index view renders this html in a div.

*Remember to set Layout to null in partial view html. 

Final output:



2. Using JSONResult and jQuery.getJSON/jQuery.ajax call:

Index view html:

We are using getJSON method of jQuery here to render the partial view.













HomeController.cs:














The return type of GetPartialView method is JSONResult. I have created a method RenderJsonViewToString to get the partial view html.

RenderJsonViewToString method:










This method calls RenderViewToString method which in turn makes use of ViewEngines to find the partial view and renders the html.









Finally it returns JSONResult to calling Index view's ajax method which then renders the output html in a div.