MS MVC形成AJAXifying技术

Arn*_*psa 12 forms ajax asp.net-mvc jquery

我正在寻找最优雅的方式来ajaxify我的表单(使用jQuery).
你怎么做到这一点?

eu-*_*-ne 12

这是我的解决方案(我认为它是一个渐进增强解决方案),只使用jQuery而没有任何插件:

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
            }
        }
    );
});
Run Code Online (Sandbox Code Playgroud)

更新:

如果你的POST响应是"HTML with form",那么试试这个:

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();
                }
            }
        );
    });
}
Run Code Online (Sandbox Code Playgroud)


and*_*ecu 6

Ajax化你的表单...这是非常模糊的.

如果要异步提交表单,可以使用$ .post()发布到单独的控制器操作.

例:

在视图中:

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

在你的控制器中:

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

这至少是我在某些形式中使用的.

PS:我在stackoverflow文本编辑器中写了这个,所以它没有真正测试过.但作为一个大纲,它应该工作.