jQuery DivFlip of MVC Partial

So you have a Partial in a div and would like to flip out the html contents with new results from just the partial… To para-phrase Obi-Wan ‘this is the JavaScript you are looking for’:

function Save() {
var data = $(‘#PartialData’).serialize();
$.post(‘SavePartial’, data, function(result) {
if (result == “success”) {
$(“#DivFlipThis”).load(“ProductUserControl”);
}
else {
alert(result);
}
});
}

It uses jQuery to serialize form data, then an Ajax post sends the data to a controller action which auto-binds it to the model. All in all there are very few lines of code. If anyone needs to see the controller actions they can be found in this tiny sample project DivFlipExample.zip (click to download). It runs stand-alone and needs no database so is MVC noob safe :)

For the projects that pay my salary (high traffic public facing websites) we have a more sophisticated technique using JSON to read a .Net class graph of errors, success message etc passed from actions to the JavaScript. The JavaScript then does a divflip, redirect to next action, shows success or error messages as applicable. It is very simple too.

So, to the MVC experts out there: Am I missing something? RoR does this kind of thing auto-magically (so our RoR team says). For hours I searched Google on how to refresh an MVC partial without doing a whole page refresh. There were many people asking the same question and lots of people like my friend Rusty Zarse becoming very frustrated, but no-one had an answer that helped us. All the demos I used to learn MVC (MVCNorthwind, MVC Commerce, MvcMembership, Suteki, MVC Storefront) need full post-backs for anything semi-significant.

This entry was posted in Uncategorized and tagged . Bookmark the permalink.