将ASP.NET MVC中的form提交改为ajax提交

在ASP.NET MVC视图中通过 @using (Html.BeginForm()) 产生的是form表单提交代码,可以用javascript代码截获这个form提交,改为ajax提交,示例代码如下:

代码来自:ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators

$('#form1').submit(function () {
    if ($(this).valid()) {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function (result) {
                $('#result').html(result);
        },
        error: function (result) {
        alert(result);
        }
    });
}
return false;
});
 

用ASP.NET MVC自带的Ajax.BeginForm也可以实现Ajax提交,但对返回结果的控制没有上面的方法灵活,代码如下:

@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "result" }))

猜你喜欢

转载自fhuan123.iteye.com/blog/2302422