In the last quick tip about MVC, we created an AJAX-enabled Partial View that used JQuery to get the data from an action method that returned JSON.

After fetching the data, we used JQuery again to add rows to a pre-existing table as a way to render our information. In the end, the view looked like this:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<script src="/Scripts/jquery.dateFormat-1.0.js" type="text/javascript"></script>

<script type="text/javascript">

 

    function formatDate(date, format) {

        var value = new Date(parseInt(date.replace("/Date(", "").replace(")/", ""), 10));

        return $.format.date(value.toString(), format);

    }

 

    $.fn.addRows = function (data) {

        return this.each(function () {

            var table = $(this);

            $(table).find("tr:gt(0)").remove();

 

            $.each(data, function (index, itemData) {

 

                var tds = "<tr>";

                tds += "<td>" + itemData.ISBN + "</td>";

                tds += "<td>" + itemData.Name + "</td>";

                tds += "<td>" + formatDate(itemData.PublishDate,"dd/MM/yyyy") +"</td>";

                tds += "</tr>";

 

                $('tbody', table).append(tds);

            });

        });

    };

 

    $.getJSON("/Home/BookList", null, function (data) {

        $("#bookList").addRows(data);

    });

 

</script>

   

<table id="bookList">

    <th>ISBN</th>

    <th>Name</th>

    <th>Publish Date</th>

</table>


And we got this result:

Partial view with AJAX and JQuery

AJAX provided us with a light-weight approach to solving our problem of passing data to a Partial View without specifically having to add that information to the ViewData dictionary or creating a composite model to pass down to our views.

The problem that most people point out regarding AJAX is that, while it’s really easy to perform the asynchronous call and fetch the data, manipulating the result on client side and create the needed rendering takes a lot of work.

You probably noticed that, even though we used JQuery, which is a very powerful Javascript library, we still had to write a lot of code in order to render our results. The resulting code is not only a bit cumbersome, but it’s also error-prone and difficult to debug.

Microsoft listened to that feedback and recognized that the developer experience for the client-side world was really poor compared to the rich environment we have on server-side. So we made three important changes that will have a very positive impact:

·        Visual Studio 2010 provides us a very powerfull Javacript Intellisense engine

·        We support JQuery in Visual Studio with full Intellisense support as well

·        ASP.NET AJAX 4 includes new AJAX controls, including client-side databinding templates (this is HUGE)

In this post, we’re going to keep it simple and just change our view to use some of the cool new stuff that is coming with ASP.NET AJAX 4.

We’ll start by adding a few script references that are included in the new ASP.NET AJAX Library and create the basic layout of our view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>

<script type="text/javascript" src="/Scripts/MicrosoftAjax/MicrosoftAjax.js"></script>

<script type="text/javascript" src="/Scripts/MicrosoftAjax/MicrosoftAjaxTemplates.js"></script>

    <table xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView">

        <thead>

            <tr>

                <th>

                    ISBN

                </th>

                <th>

                    Name

                </th>

                <th>

                    PublishDate

                </th>

            </tr>

        </thead>

        <tbody>

        </tbody>

    </table>


Notice we’re adding two script references in our view. Both scripts are included in the new ASP.NET AJAX Library. After that, in order to use a new control called a DataView, we need to define two namespace prefixes. Usually, we define this in the body tag, but as you can see here, it can be defined in any element (in this case, the table element).

For now, the table body is empty. We’re obviously going to fill it with the retrieved data (which we haven’t fetched yet), but instead of iterating through the results and adding rows to the table, we want to simply specify an HTML template to be applied to each result.

<tbody class="sys-template" id="master" sys:attach="dataview" dataview:autofetch="true"

    dataview:dataprovider="/Home/BookList"

    dataview:selecteditemclass="myselected">

    <tr sys:command="select">

        <td>

            {binding ISBN }

        </td>

        <td>

            {binding Name }

        </td>

        <td>

            {binding PublishDate }

        </td>

    </tr>

</tbody>


If you ever used WPF databinding, you’ll feel right at home here. Notice that we are attaching a dataview to the tbody element. The next attributes are there to define the behavior of the dataview control:

·        autofetch: specifies that the AJAX call will be made immediately after the page is loaded

·        dataprovider: specifies where to fetch the data from. In this case we’re just pointing to our action method which returns JSON, but we could point it to a WCF Service or an ADO.NET Data Service as well.

·        selecteditemclass: the dataview supports the select command, this attribute defines which CSS class should be applied to the selected data record

Whatever we add inside the scope of the dataview, basically represents a template that will be applied to each data record we get. Notice how similar this is to server-side databinding, which is one of the most appreciated features of ASP.NET. Microsoft decided to bring that experience down to the client-side level aswell.

Believe it or not, you don’t need to do anything else. If you now start your application, this will be the result:

partial view with ajax dataview

Notice that we are able to select a row of data just by clicking on it:

dataview with selected row

This actually triggers a select command but we aren’t doing anything with it currently. In my next post I will talk a bit more about ASP.NET AJAX 4, showing you how to create a master-detail view with two way databinding, using these new controls and no Javascript code whatsoever.

Until then, have fun!