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.

Advertisements
This entry was posted in ASP.Net MVC. Bookmark the permalink.

2 Responses to jQuery DivFlip of MVC Partial

  1. Rusty says:

    Ah, very good! Thanks for this. I FINALLY found a way to render partial from the Controller. I blogged about RenderUserControl to RenderPartial migration

    Overall, I am notunhappy with MVC Beta but I do miss some of what was stripped. Nonetheless, I feel down right dirty using web forms and post back 🙂

  2. Paul Lockwood says:

    Web Forms? Ugh, sorry to hear it got that bad!

    Hopefully the trailblazing dust around MVC will settle soon and we will have commonly accepted/ used techniques – until then people like us are having a roller-coaster ride 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s