Ajax Post上的MVC验证

时间:2014-09-16 20:14:19

标签: jquery asp.net-mvc-4 ajaxform

我使用MVC4,我想将我的页面从客户端发布到服务器,我使用ajax post方法发布我的提交数据。

$("#btn").click(function(){
    $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '/Admin/Create/',
                //data: JSON.stringify(datatosend),
                crossDomain: true,
                dataType: "json",
                success: function (data) {
                    if (data.redirectUrl != null) {
                    window.location = data.redirectUrl;
                    }
})
});

而不是<input type="submit" value="add">使用<input type ="button" value="add" id="btn"> 并点击方法调用ajax帖子。 当我使用提交类型时,验证工作正常,但在按钮类型上,vaidations不起作用,并且页面在成功后也不会重定向。 我看过很多关于这个问题的帖子。但无法找出原因

2 个答案:

答案 0 :(得分:1)

click处理程序中执行以下操作:

var isValid = $(this).closest("form").validate();
if (isValid) {

    // do ajax post
}

或者,您可以查看文档,它有不同的方法:

http://jqueryvalidation.org/validate

答案 1 :(得分:0)

1.要解决验证错误,您可以执行以下代码。

$("#btn").click(function(){


var form = $("#myform").validate();

if(form.valid())
{
    $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '/Admin/Create/',
                //data: JSON.stringify(datatosend),
                crossDomain: true,
                dataType: "json",
                success: function (data) {
                    if (data.redirectUrl != null) {
                    window.location = data.redirectUrl;
                    }
                error: function (errorResponse) {
                    alert(errorResponse.responseText);
                    }
           })
}

});

2.为什么你的页面没有被重定向检查几点。

  • 检查您是否以JsonResult
  • 为动作返回Json结果
  • 值应使用引号window.location = '';