Snuggle up to jquery $.ajax

Tags: MVC, jQuery, Ajax

In an earlier post I described how to use the MVC 3 Ajax.ActionLink to post an async delete back to the server. Ajax.ActionLink depends upon jquery.unobtrusive-ajax.js, a script included with the MVC 3 project template. As Brad Wilson has blogged, and I demonstrated, you create an AjaxOptions class and pass it into the ActionLink method constructor. When the view is rendered those properties are emitted with the anchor tag as HTML 5 data-* attributes:

<a data-ajax="true" 
   data-ajax-confirm="Are you sure you want to delete this widget?" 
   data-ajax-method="POST" 
   data-ajax-success="deleteConfirmation" 
   href="/Widget/Delete/1">Delete</a>

Enter the jquery.unobtrusive-ajax.js script. I won't go into too much detail (because you can see it for yourself) but essentially the asyncRequest function takes those HTML 5 data attributes and builds a call to the jquery $.ajax function. Is it just a wrapper? Well yes, but a very convenient one because it promotes strong typing in your razor view and saves you from the messy details of creating a $.ajax function call on your own.

If you don't like the Ajax.ActionLink helper you're always free to roll your own. And it's easy. Take the same project from my previous blog post. Nothing changes with the Widget and WidgetController classes. Now in the Index.cshtml file replace the Ajax.ActionLink with a plain old anchor tag:

<a href="javascript:void(0)" id="@item.Id" class="delete-widget-link">Delete</a>

Then replace the script region with the following ajax funtion call:

<script type="text/javascript">
 
    $('.delete-widget-link').click(function() {
        // get the id of the selected widget
        var id = $(this).attr("Id");
 
        // delete on server
        $.ajax({
            type: "POST",
            url: "Widget/Delete/" + id,
            success: handleDeleteSuccess,
            error: function () {
                $('#actionMessage').text('Delete failed...');
                $('#actionMessage').effect("highlight", {}, 3000);
            }         
        });
    })
 
    function handleDeleteSuccess(data) {
        // remove the row from the table
        var rowId = "#widget-id-" + data.id;
        $('.widgets').find(rowId).remove();
 
        // display a status message with highlight
        $('#actionMessage').text(data.message);
        $('#actionMessage').effect("highlight", {}, 3000);
    }
    
</script>

That's it. You're still unobtrusive. But you're now making a direct call to the jquery $.ajax function instead of going through the jquery.unobtrusive-ajax.js script.

Add a Comment