Sunday, November 27, 2011

More Ajax with MVC – Using Partial Views with Ajax

One the the really nice features in mvc is the ability to use partial views, not only for breaking up pages and reusing content but also for doing Ajax calls.  In Easy Ajax with ASP.NET MVC and jQuery I showed you how to do a basic Ajax call and display the data returned, now I’m going to show you something a little more useful, actually retuning content to display on the page.
First we take this partial view
   1: @using SampleApplication.Models
   2: @model PartialModel
   4: <div>
   5:     @Model.Text
   6: </div>
   7: <input type="button" value="click me" onclick="UpdateView();return false;"/>
Then we add it to the main view like this
   1: <div id="UpdateableContent">
   2:     @{ Html.RenderPartial("Partial",new PartialModel{Text = "Before Clicked"}); }
   3: </div>
Next we need to have a Action to call that returns the rendered view with updates
   1: public ActionResult UpdatePartial()
   2: {
   3:     var model = new PartialModel() {Text = "was updated"};
   4:     return View("Partial", model);
   5: }
In this case we update the model and return the specified partial view with the updated model.

Last we have the Javascript that makes the Ajax call
   1: function UpdateView() {
   2:     var model = { };
   3:     $.post("/home/UpdatePartial",
   4:         model,
   5:         function (data) {
   6:             $("#UpdateableContent").html(data);
   7:         });
   8: }
it’s fairly simple and a lot like what we did in the Easy Ajax post, the major difference is we take the returned rendered partial view and replace the existing rendering of the partial view using JQuery’s .html(),  this replaces the existing content with the passed in content.  This is a very simple and effective way to manipulate your pages.

As always here is the source code for a sample project using it