Specifying a Partial View

In addition to returning a view, an action method can also return a partial view in the form of a PartialViewResult via the PartialView method. Here's an example:

public class HomeController : Controller {
    public ActionResult Message() {
        ViewBag.Message = "This is a partial view.";
        return PartialView();
    }
}

In this case, the view named Message.cshtml will be rendered, but if the layout is specified by a _ViewStart.cshtml page (and not directly within the view), the layout will not be rendered.

The partial view itself looks much like a normal view, except it doesn't specify a layout:

<h2>@ViewBag.Message</h2>

This is useful in partial update scenarios using AJAX. The following shows a very simple example using jQuery to load the contents of a partial view into the current view using an AJAX call:

<div id="result"></div>

<script type="text/javascript">
$(function(){
    $(‘#result’).load(‘/home/message’);
});
</script>

The preceding code uses the jQuery load method to make an AJAX request to the Message action and updates the DIV with the id result with the result of that request.

To see the examples of specifying views and partial views described in the previous two sections, use NuGet to install the Wrox.ProMvc3.Views.SpecifyingViews package into a default ASP.NET MVC 3 project like so:

UnFigure
Install-Package Wrox.ProMvc3.Views.SpecifyingViews

This ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.