views:

316

answers:

1

Hi,

I'm new to ASP.NET MVC and jQuery, so I thought I'd share how I implemented loading of partial views and submitting forms in a way that doesn't require for the entire page to be refreshed. I hope to get some critique from the experts if there's a better way to do this :)

All the magic is done by 3 javascript functions which I bind to various events, like button click, jQueryUI tab select, etc.

Firstly, this is how I get a partial view:

function showAjaxMessage(targetDiv, ajaxMessage) {    
    var ajaxLoader = "<img src='Content/loader.gif' alt=''>";
    $(targetDiv).html("<p>" + ajaxLoader + " " + ajaxMessage+"</p>"); 
}

function getPartialView(actionUrl, targetDiv, ajaxMessage, callback) {
    showAjaxMessage(targetDiv, ajaxMessage);

    $.get(actionUrl, null, function(result) {
        $(targetDiv).html(result);
        callback();
    });
}

Usage:

getPartialView("MyController/MyAction", "#myDiv", "Loading...", function() { alert('Loaded!'); });

This will set whatever the action returned (PartialView) as the content of myDiv and then invoke the callback function (in this case, it will just pop up an alert) with a nice "Loading..." message displayed in the div while we wait for the response.

Secondly, submitting a form:

function submitForm(actionUrl, targetDiv, ajaxMessage, form, callback) {

    var data = $(form).serialize();
    showAjaxMessage(targetDiv, ajaxMessage);
    $.post(
        actionUrl,
        data,
        function(data) {
            $(targetDiv).html(data);
            callback();
        }
    );
}

Usage:

submitForm("MyController/MyAction", "#myDiv", "Submitting...", "#myForm", function() { alert('Submitted!'); });

Once again, this invokes a controller action, but this time it does a POST with the given form's data (<form id="myForm">) serialized as "input1=value1&input2=value2&...&inputn=valuen", allowing the action to do something with the user input, like so:

public ActionResult MyAction(FormCollection form)
{
    // eg. TryUpdateModel<MyActionViewModel>(this.myActionViewModel);
    // or 
    // do something with form["input1"] ...

    return PartialView("MyPartialView", this.myActionViewModel);
}

The HTML returned is once again rendered into myDiv and a callback function is invoked.

I haven't added any validation as yet, but the basics work quite nicely, but if there is a better way, please share :)

+2  A: 

I'd just use jQuery.taconite:

Mauricio Scheffer