Partial page updates with jQuery and MS MVC

Just a quick and dirty, as I’m not going to go into all the details of neither jQuery nor MS MVC.  But I wanted to show a easy way to use jQuery to get ajax callbacks with MS MVC.

In my View I have a select tag as follows:

<%= Html.Select("selectList", ViewData.AirSummaryList, "PilotName", "ID") %> 
 

This is data that is bound to the list.  In the header of the View I have a call setup to make the ajax call:

$(document).ready(function(){
          $("#selectList").change(function(e){
               $("#selectList option:selected").each(function(){
                    var t = $(this).text()
                    $.post("/Home/AJAXTest", {
                        content: t
                    },function(txt){
                         $('#showResults').html(txt).show();
                    });


            });
          });
      });

The “/Home/AJAXTest” is a call to the HomeController and the AJAXTest action.  Content ‘t’ is the data being passed to the action:

public void AJAXTest(string content)
        {
            PassThroughData data = new PassThroughData();
            data.Name = content;
            RenderView("ViewUserControl1", data);
        }

I have created a new ‘MS MVC User Control’ and the data will be sent to this ‘control’ and rendered inside the ‘showResults’ div (see javascript above), as well as a structure to pass the data with (I prefer this route):

public partial class ViewUserControl1 : System.Web.Mvc.ViewUserControl<PassThroughData>
    {
    }

    public struct PassThroughData
    {
        public string Name{get;set;}
    }

With the ViewData being set to ‘PassThroughData’, inside the control’s view it’s easy to display the data:

Hello <%= ViewData.Name %>

I like this way of handling callbacks with MS MVC.  jQuery makes it fairly easy to use as well.

Note: you can use a ‘get’ as well :

 

$.get("/Home/AJAXTest", {
                        content: t
                    },function(txt){
                         $('#showResults').html(txt).show();
                    });

Also, just to show how your view could continue to use jQuery, inside the view that is loaded via the callback:

<script type="text/javascript">
$('#selectedPilot').click(function()
                        {
                           alert($(this).text());
                        });
</script>
<div id="selectedPilot"><i>You have selected</i> <b><%= ViewData.Name %></b></div>

Advertisements

One thought on “Partial page updates with jQuery and MS MVC

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