【发布时间】:2012-11-10 01:23:39
【问题描述】:
我正在对 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,然后才会调用该操作,但为时已晚。不幸的是,例外是空的。之后视图立即关闭。
【问题讨论】:
-
服务器抛出了什么异常?
-
动作中没有异常 - 动作中的代码按预期运行。错误函数中的异常对象为null。
-
你得到了什么 HTTP 响应代码?如果您不知道如何检查,请尝试使用 Firebug for Firefox 或 Chrome 中的开发人员工具。
-
响应是预期的 JsonResult:{"Success":true,"Message":"您的联系人已成功创建!"}
标签: ajax asp.net-mvc