MS MVC form AJAXifying techniques [closed]

I'm looking for most elegant way to ajaxify my forms (with jQuery).
How do you do this?


Solution 1:

Here is my solution (I think it is a Progressive enhancement solution), using only jQuery without any plugins:

var form = $('form#YourFormId');
$(':submit', form).click(function (event) {
    event.preventDefault();
    $.post(form.attr('action'), form.serialize(),
        function(data, status) {
            if(status == 'success') {
                // your code here
            }
        }
    );
});

UPDATED:

If your POST response is "HTML with form" then try this:

function ajaxifyForm(form) {
    $(':submit', form).click(function (event) {
        event.preventDefault();
        $.post(form.attr('action'), form.serialize(),
            function(data, status) {
                if(status == 'success') {
                    var newForm = $(data);
                    ajaxifyForm(newForm);
                    form.after(newForm).remove();
                }
            }
        );
    });
}

Solution 2:

Ajaxify your forms... that is pretty vague.

If you want to submit a form asynchronously, you could use $.post() to post to a separate controller action.

Example:

In the view:

$.post('<%= Url.Action("DoAjaxCall") %>', $('form').serialize(), 
function (data) {
    alert(data.Message);
}
, "json");

In your controller:

public ActionResult DoAjaxCall(YourModel model)
{
    return Json(new { Message = "Your ajax call is working!" });
}

That is what I'm using in some of my forms at least.

P.S.: I wrote this in the stackoverflow text editor so it's not really tested. But as an outline, it should work.