.NET Tips and Tricks

Blog archive

Integrating Ajax and Partial Views in ASP.NET MVC

In previous columns, I've discussed options in assembling your View from a set of partial Views. However, in all of those examples, I've been assembling a View on the server in response to a request from the client.

The cool thing is that you can also return partial Views to Ajax calls. Here's a getJson call to a ASP.MVC Controller's Action method that expects to get back a set of HTML that it inserts into a page's div element:

$.ajax({
        data: InfoAndData,
        datatype: "text/plain",
        type: "POST",
        url: 'MyController/MyAction',
        cache: false,
        success: function (data) {
                $('#divDisplay').html(data);
            }
        });

The Action method, accepts the data from the Ajax call in the same way as it does any other request but uses the PartialView method to trigger processing of the partial View and have the resulting HTML sent to the client:

Public Function MyAction(InfoAndData As InfoClass) As ActionResult
   ... code to retrieve data based on values in InfoAndData ...
   ... load results ... 
  Return PartialView("MyView", results)
End Function

There are lots of things to like about this approach -- having your HTML generated in a View is consistent with the way that the rest of your HTML is created. You also have access to all of Razor's tools for creating HTML (including localization). Finally, of course, your client-side code is reduced because you don't have to write the code to insert each data item into the page.

But there are at least two things to dislike: The payload being returned (HTML + data) is almost certainly going to be larger than the equivalent JSON object holding just the relevant data. The cycles required to generate the HTML may or may not be equivalent to cycles required to insert the data/set up the HTML on the client.

However, the server-side cycles are on a shared resource while the client-side cycles are on the user's computer. Using server-side cycles makes your application less scalable (personally, I feel that the user's computer should be regarded as free, unlimited resource that should be exploited mercilessly).

For me, I like using partial Views enough (and regard the costs of sending partial views as sufficiently low) that I frequently use this technique.

Posted by Peter Vogel on 06/30/2015


comments powered by Disqus

Featured

Subscribe on YouTube