Thursday, 19 May 2011

Automatic AJAX-ification of forms

I've only been doing ASP.net MVC/jQuery a few months but this came as a real "a-ha!" moment to me. To display an AJAX jQuery UI dialog instead of navigating to a new page, simply adorn your links with a class such as "open-dialog" and give them a title attribute:
    Do Something
then in your script, you can simply use this call:
    $('a.open-dialog').click(function () {
        var title = $(this).attr('title');

        $('<div><div>).dialog({
            buttons: {
                OK: function () {
                    $('form', this).submit();
                    $(this).dialog('close');
                },
                Cancel: function () {
                    $(this).dialog('close');
                }
            },
            modal: true,
            title: title
        }).load($(this).attr('href'));

        return false;
    });
This will display a dialog with the contents and title of the link instead of navigating to a new page. Make sure that in your controller you call Request.IsAjaxRequest() and if this returns true, return a Partial containing only the content to show in the dialog.

No comments:

Post a Comment