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 will add a sample controller to your project in the samples directory with multiple action methods, each specifying a view in a different manner. To run each sample action, press Ctrl+F5 on your project and visit:

  • /sample/index
  • /sample/index2
  • /sample/index3
  • /sample/partialviewdemo
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.242.157