RSS

ASP.NET MVC – PartialView with Ajax

12 Apr

In this post I will briefly discuss how to use a PartialView either as a Web Form’s “UserControl” or as an “UpdatePanel”. You can click on the links to navigate accordingly, or just read on. UPDATE: If you’d rather have a “real world” example, you can read this post: http://evolpin.wordpress.com/2011/04/26/asp-net-mvc-partial-view-and-ajax-real-world-example/.

I’ve wanted to use a PartialView for quite some time now. A PartialView provides two functionalities which aren’t necessarily overlapping although have much in common. In comparison with Web Forms, a PartialView is a kind of a UserControl, but it also provides a kind of UpdatePanel.

What’s great about a PartialView is that it’s very straight forward – you simply place your HTML and/or JavaScript in a separate View file, probably placed in your Shared views folder so it can be used easily across views. Then you can either use it as a control, by placing Html.Partial(…) calls on your View as desired, or you can render it in run-time as a response to an Ajax call.

UserControl like implementation:

Let’s go quickly over the first usage, that of a “UserControl”: we right-click on the Shared folder to add a new View, give it a name, and select the “Create as a partial view” checkbox:

Our solution explorer looks as follows (Index.cshtml will be using the newly created MyPartialView.cshtml):

MyPartialView contains a simple dummy html place holder which will display a “My View” header; whereas Index.cshtml in this example will now include 2 references to MyPartialView:

1: <table border='1'> 
2:     <tr>
3:         <td>
4:             @Html.Partial("MyPartialView")
5:         </td>
6:         <td>
7:             @Html.Partial("MyPartialView")
8:         </td>
9:     </tr>
10: </table>

That’s about it, and this is how it looks:

One more thing worth mentioning, is that the ViewData dictionary which can be populated in the Controller, is available both to the View and to it’s Partial Views.

Ajax and html injection – “UpdatePanel”:

As I mentioned earlier, Partial Views can also provide a functionality resembling Web Form’s UpdatePanel. Those familiar with UpdatePanel usually either appreciate the (relatively) ease of use, or despise it for being so heavy and inefficient. Almost an Ajax “wannabe”. Personally, I think that UpdatePanel has its place in Ajax side by side with PageMethods/WebMethods. I consider it the better alternative for rendering a “mass” of html onto the client, especially when paging or sorting grids. In MVC, a PartialView could perform this exact functionality, and could prove to be the better solution for rendering plenty of html to the client.

Basically there are 4 steps to achieve this:

  1. Create a PartialView.
  2. Create a place holder html control.
  3. Use jQuery’s load method to fetch the partial view from the server and inject it into the place holder.
  4. Create a server side Action in a Controller that will return the partial view.

Here’s a quick example how this can be done. We’ll use the same partial view created earlier (i.e. MyPartialView.cshtml). So now we have to prepare a place holder div, and use jQuery to load and inject the response:

1: <a href='javascript:getView();'>Get Partial View</a>
2: <script type="text/javascript">
3:     function getView() {
4:         $('#divResult').load("@Url.Action("GetView" , "Home" )");
5:     }
6: </script>
7: <div id='divResult'>
8: </div>
  • Line 1 is a simple anchor which will invoke the JavaScript containing jQuery’s load.
  • Line 4 is the simple one-line code which performs an ajax call to the server’s GetView action in the Home Controller (will be done shortly), and injects the result.
  • Line 7-8 is where the result will be injected to.

And now for the server side – pretty self-explanatory:

1: public ActionResult GetView()
2: {
3:    return PartialView("MyPartialView");
4: }

When we run the sample, prior to the Ajax call this looks like this:

After clicking the link, jQuery’s load method performs the Ajax call as expected, and the partial view’s HTML is injected into the place holder. All this can be viewed in the picture below:

  1. The load method performs a GET operation to the server’s GetView.
  2. Response is returned with html.
  3. jQuery injects the result in the place holder div.
  4. The result is rendered in the browser.

That’s it! No doubt this is real simple to achieve. From here on, the possibilities are quite remarkable. You see, it turns out that when jQuery injects the code, it is also able to inject JavaScript. This means that you can actually render not only html, but JavaScript code as well. Naturally you can argue if this is a good thing or not, but it just gives you a hint on how extensible this can be.

As usual, credits are in order. This great post summarizes different jQuery Ajax approaches with ASP.NET MVC.

BTW: If you ask yourself why you should use jQuery instead of Microsoft Client libraries, I guess you should relate to Microsoft’s statements about “throwing its weight behind jQuery”. You can read about this in Stephen Walther’s blog. Stephen’s conclusion says it all: “Our plan is to focus on jQuery as the primary technology for building client-side Ajax applications moving forward. We want to adapt Microsoft technologies to work great with jQuery and we want to contribute features to jQuery that will make the web better for everyone. We are very excited to be working with the jQuery core team.” Although MVC 3 comes with Microsoft Ajax client scripts, it also includes jQuery and I guess that we’ll see more and more of jQuery in Microsoft’s VS templates.

About these ads
 
12 Comments

Posted by on 12/04/2011 in Software Development

 

Tags: , , , ,

12 responses to “ASP.NET MVC – PartialView with Ajax

  1. Benjamin

    02/06/2011 at 17:32

    Hey, that’s nice and easy. Thanks!

     
  2. ijwo

    10/07/2011 at 13:34

    WOW simple and easy to understand for a noob like me. thanks for this post

     
  3. abc

    08/02/2012 at 07:33

    Good One :)

     
  4. Veeru

    12/02/2012 at 19:31

    Thanks for the good article! Can you please send the code to veerugadde@gmail.com

     
  5. CADAVID

    21/02/2012 at 04:01

    good example..can you please send this code to me carll167@gmail.com blessings

     
  6. Ami

    27/03/2012 at 14:45

    Can I make a call to a POST action of controller using above example… please help me as I m suppose to save some data to DB without refreshing the whole page.

     
    • evolpin

      28/03/2012 at 00:17

      @Ami,

      According to jQuery documentation, if ‘load‘ is passed data as an object, it uses POST:

      The POST method is used if data is provided as an object; otherwise, GET is assumed.

      However, if you’re not intending on downloading a Partial View, you might consider using a simple $.post.

       
  7. Lalit

    24/08/2012 at 09:19

    @evolpin and @Ami,
    Sorry to say, but it doesn’t worked for me. What i did: I took the text box and button control under the user control. where as on click, redirect to Post action for the same. in Post action there is viewdata with hard code string. i supposed to be render the that hard coded View Data to label taken on same user control. but alas, it was not. while debugging it was showing me the value of view data in immediate window but after render there is no impact on page.

    Conclusion : I think we can not perform Post-Render approach with above given approach. since ideally people looks for the solutions, where update panels manipulates with database and assumes entered transaction should view on same page without refresh whole page.

     
  8. enko

    29/08/2012 at 00:29

    Thanks for keeping it simple.

     
  9. Jayden Bellus

    08/05/2013 at 16:16

    Hi!

    This is a nice article. Thank for sharing your knowledge. There are some other links related to “Calling partial view using Ajax in ASP.NET MVC 4″. I hope this is a

    very useful for developers.

    http://www.mindstick.com/Articles/8e131adf-2621-4cd7-8557-770c1ede799c/?Calling%20partial%20view%20using%20Ajax%20in%20ASP.NET%20MVC%204

    http://ciintelligence.blogspot.in/2012/06/aspnet-mvc-ajax-load-with-partial-view.html

     
  10. Vivekanand Singh

    17/06/2013 at 10:38

    Thank u so much…

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 66 other followers

%d bloggers like this: