为什么我的 AJAXoned 操作的 return 没有被调用者视为成功?

Why is my AJAXoned Action's return not being seen as successful by the caller?

在我的 ASP.NET MVC 应用程序中,我在我的视图的脚本部分得到了这个 AJAX 调用:

$(".ckbx").change(function () {
. . .
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetUnitReportPairVals", "Home")',
        data: { unit: unitval, report: rptval },
        cache: false,
        success: function (result) {
            alert(result);
        }
    });
});

单步执行正在调用的控制器操作:

public ActionResult GetUnitReportPairVals(string unit, string report)
{
    HomeModel model = new HomeModel();

    int rptId = GetReportIDForName(report);

    DataTable UnitReportPairEmailValsDT = new DataTable();
    UnitReportPairEmailValsDT = SQL.ExecuteSQLReturnDataTable(
        SQL.UnitReportPairEmailQuery, 
        CommandType.Text, 
        new SqlParameter()
                {
                    ParameterName = "@Unit",
                    SqlDbType = SqlDbType.VarChar,
                    Value = unit
                },
                new SqlParameter()
                {
                    ParameterName = "@RptID",
                    SqlDbType = SqlDbType.Int,
                    Value = rptId
                }
                );

    model.UnitReportPairEmailVals = UnitReportPairEmailValsDT;
    return View(model);
}

...似乎一切正常; "model" 包含 UnitReportPairEmailVals 中的预期值。

但我从未在 Ajax 调用中看到来自此处的警报消息:

success: function (result) {
    alert(result);
} 

那么为什么jQueryAJAX调用的"success"函数没有到达呢?

更新

顺便说一句,这可能是一个线索:我的控制器方法的最后一行:

return View(model);

...将 "View" 一词涂成红色,就像罗德岛公鸡的鸡冠一样。但如果它不应该是那样,它应该是什么?这与我在 "public ActionResult Index()" 控制器操作结束时所拥有的完全相同,它工作正常。

更新 2

我将 Ajax 通话的结尾更改为:

success: function (result) {
    alert(result);
},
failure: function (error) {
    alert(error);
}

...以及我的控制器方法的结尾:

return Json(new { Result = model }, JsonRequestBehavior.AllowGet);

...但我没有收到任何警报,无论是成功还是失败。

更新 3

注意:当我尝试这个时:

var model = JSON.stringify({ unit: unitval, report: rptval });
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetUnitReportPairVals", "Home")',
        data: model,
        contentType: 'application/json',
        cache: false,
        success: function (result) {
            alert(result);
        },
        error: function (result) {
            debugger;
        }
    });

..."unit" 为空,所以它根本不会飞。

当我将其更改为这个时(删除了第 1 行并将 "data" arg 更改回我之前使用的内容):

$.ajax({
    type: 'GET',
    url: '@Url.Action("GetUnitReportPairVals", "Home")',
    data: { unit: unitval, report: rptval }, 
    contentType: 'application/json',
    cache: false,
    success: function (result) {
        alert(result);
    },
    error: function (result) {
        alert('failed');
    }
});

..."unit" 是我所期望的(以及 "report"),但我最终看到了 'failed'.

更新 4

在我拼凑出这个问题和相关问题的几个不同答案后,我写了一篇关于如何做到这一点的提示 here

更新 5

我有这个 [working] ajax call [working]:

var model = JSON.stringify({ unit: unitval, report: 1 });
$.ajax({
    type: 'GET',
    url: '@Url.Action("GetUnitDataRangeParamsVals", "UnitReportDataRangeParams")',
    data: { unit: unitval, report: 1 },
    contentType: 'application/json',
    cache: false,
    success: function (returneddata) {
        populatedatarangeprams(1, returneddata);
    },
    error: function () {
        alert('error - returneddata.error.stringify');
    }
});

...但我没有使用已声明的 "model",根据我的理解,它与 "contentType: 'application/json',"

配对

所以我想我应该做的是这样的:

var model = JSON.stringify({ unit: unitval, report: 1 });
$.ajax({
    type: 'GET',
    url: '@Url.Action("GetUnitDataRangeParamsVals", "UnitReportDataRangeParams")',
    data: model,
    contentType: 'application/json',
    cache: false,
    success: function (returneddata) {
        populatedatarangeprams(1, returneddata);
    },
    error: function () {
        alert('error - returneddata.error.stringify');
    }
});

现在传递给控制器​​方法的数据是 json 字符串化格式(封装在 "model" 中)。

但是,它甚至不起作用。

它适用于第一个块,但不适用于第二个。

所以我删除了 "model" 和 "contentType" 行,并将 "data" 行改回原来的样子,并且工作正常。那么它们是没用,还是我用错了?

以下是我在 ASP.NET MVC 中执行 ajax 时使用的一些片段。

$(".ckbx").change(function () {
    .....
    var model = JSON.stringify({ unit: unitval, report: rptval });
    $.ajax({
        type: 'GET',
        url: '@Url.Action("GetUnitReportPairVals", "Home")',
        data: model,
        contentType: 'application/json',
        cache: false,
        success: function (result) {
            alert(result);
        },
        error: function(result) {
            debugger;
        }
    });
});

有时这两个更改(与您的原始版本相比)不是必需的,但如果 json 不正确,ASP.NET 可能会有点挑剔,这有助于解决这个问题。由于您能够进入控制器方法,这不是您的问题,但它可以派上用场。

您真正的问题是控制器方法上的 return 类型。 ActionResult 意味着它将寻找相应的视图并根据该视图构建 html。但如果你正在做 ajax 那么你可能不想要那样。

public JsonResult GetUnitReportPairVals(string unit, string report)
{
    // do some stuff
    // then create response model
    var model = ...//whatever data you are returning here
    return Json(model);
}

这是 ASP.NET MVC 中 ajax 调用的 "standard" 方法。

正如您在评论中指出的那样,ActionResult 在 Index 方法中运行良好。是的,因为 index 方法的目的是加载页面。通常,如果该方法用于加载页面,那么您将使用 ActionResult,因为它将使用视图为该页面创建 html。但是,如果您只是提交信息,然后 return 收到 "success" 之类的回复,那么您不需要整个 html 回复,您需要 json。这就是 JsonResult 在这里工作的原因。

我怀疑您没有为此操作创建视图,这会导致 ajax 调用在异常情况下失败,因为 razor 引擎将无法找到该视图。确保此操作存在视图,或者如果您想要 return 一些其他视图,请指定:

 return View(model,"ViewName");

你也可以添加失败回调,看看哪里出了问题:

success: function (result) {
            alert(result);
        },
error: function(error){
           console.log(error);
        }

更新:

如果你只想 return 数据然后使用 Json:

return Json(new {Result = model },JsonRequestBehavior.AllowGet);