ASP.NET MVC3 : Loading Partial View with jQuery

This website is no longer actively supported

Written by John DeVightJohn DeVight on 13 Jun 2011 18:43

Overview

I recently had a need to render a partial view after the page had been loaded in the browser. I was able to accomplish this by using the jQuery.ajax() function.

Creating the Partial View

Creating the partial view was straight forward. The on thing that I needed to make sure that I did was to set the Layout for the partial view to null. If no Layout is specified for the partial view, the RazorViewEngine selects a Layout for the partial view.

Here is the code that should appear at the top of the partial view right after the @model:

@model MyApplication.Models.Section
@{
    this.Layout = null;
}

Implementing a Method in the Controller

The model for the view is based on user input. The user input needed to be passed to a method in the controller so that the model gets populated with the correct data. The method's parameter names need to match the parameter names as they are defined in the jQuery.ajax() call.

Here is an example:

namespace MyApplication
{
    public class DocumentController : Controller
    {
        public ActionResult GetSection(string documentType, string sectionName)
        {
            // Code here to get a section...

            return View(section);
        }
    }
}

Implementing the Client-Side Code

An event on the client side triggers the call to jQuery.ajax() to load the partial view in a div that is defined in the page. Assuming that the HTML for the div is:

<div id='sectionContents'></div>

Here is the jQuery call to populate the div:

$.ajax({
    url: '/Document/GetSection/',
    contentType: 'application/html; charset=utf-8',
    type: 'GET',
    dataType: 'html',
    data: {
        documentType: $('#DocumentType').val(),
        sectionName: $('#SectionName').val()
    }
})
.success(function(result) {
    // Display the section contents.
    $('#sectionContents').html(result);
})
.error(function(xhr, status) {
    alert(xhr.responseText);
});

References

Comments

Add a New Comment

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License