This website is no longer actively supported
Written by John 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
- jQuery.ajax(): http://api.jquery.com/jQuery.ajax/
Fantastic, works like a charm.
This is great. Maybe this is a silly question, but is there a way to get a model value into the data attribute? ie data: { documentType: @Model.SomeValue}
thanks, it helped!
why are you not returning view as PartialView
In your controller
namespace MyApplication
{
public class DocumentController : Controller
{
public ActionResult GetSection(string documentType, string sectionName)
{
// Code here to get a section…
return PartialView(section);
}
}
}
like a boss, thanks