It depends entirely on your application. I've both had the action return pure data (usually JSON, not XML) and handled the display in the client and had the action return a partial view. For most complex display scenarios, I think the partial view route is easiest. Essentially, you are returning just the portion of the page (HTML) that is going to be updated. You use javascript in the AJAX callback handler to replace the appropriate element(s) on the page with the HTML you get back from the server. Note that you need to be careful with event handler binding when you do this -- it's almost always the right thing to do to use live handlers in jQuery 1.4+ and rebind all but click handlers in jQuery 1.3.
Example: Assumes that you are calling an MVC action method that returns a partial view. This will call the show
action on the foo
controller every 5 seconds and update the containerToUpdate
(presumably a DIV), with the html returned.
setInterval(
function() {
$.get( '<%= Url.Action( "show", "foo", new { id = Model.ID } ) %>',
function(html) {
$('#containerToUpdate').html( html );
});
}, 5000
);
Server side:
[AcceptVerbs( HttpVerbs.Get )]
public ActionResult Show( int id )
{
var model = ...
if (this.Request.IsAjaxRequest())
{
return PartialView( model );
}
else
{
return View( model );
}
}
The full view (for non-AJAX) may not be necessary -- you may want to just display an error if the user shouldn't be accessing this except through AJAX. If you do support both, just render the partial inside the full view where it's needed so that you reuse the partial view code.