MVC3 AJAX操作请求:处理答案



我正在对MVC3操作进行AJAX请求,我想在成功或错误函数中处理JSONRESULT。当前的行为很奇怪:在击中我的断点之前,它会击中错误函数。谁能帮我并有提示?

我的观点:

<form id="myForm">
    //fields go here...
    <button id="myButton" onclick="myFunction();">ButtonName</button>
</form>

ajax调用:

function myFunction() {    
if ($('#myForm').valid() == false) {
    return;
}
var data = {
    val1: $("#val1").val(),
    val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
    url: url,
    type: 'POST',
    dataType: 'json',
    cache: false,
    data: data,
    success: function (data, statusCode, xhr) { 
        alert('1');
        if (data && data.Message) {
            alert(data.Message);
            alert('2');
        }
        alert('3');
    },
    error: function (xhr, errorType, exception) { 
        alert('4');
        var errorMessage = exception || xhr.statusText; 
        alert("There was an error: " + errorMessage);
    }
});
return false; 

}

我的动作:

[HttpPost]
    public ActionResult Action(Class objectName)
    {
        var response = new AjaxResponseViewModel();
            try
            {
                var success = DoSomething(objectName);
                if (success)
                {
                    response.Success = true;
                    response.Message = "Successful!";
                }
                else
                {
                    response.Message = "Error!";
                }
            }
            catch (Exception exception)  
            {  
                response.Success = false;  
                response.Message = exception.Message;   
            }
            return Json(response); 
    }

如果您在Ajax调用中查看,我会直接获得警报#4,只有这样调用,该操作才会为时已晚。不幸的是,例外是无效。之后直接关闭视图。

您没有阻止默认的onclick行为。您可以尝试以下内容吗?

onclick="return myFunction()"

最新更新