JQuery Ajax Post - 操作返回部分视图,但未成功或显示

CJH*_*CJH 2 asp.net-mvc post asp.net-ajax

我正在调用控制器操作,如下所示:

$j.ajax({
    url: url,
    type: "post",
    data: JSON.stringify(commentParam),
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    success: function (data, status, jqxhr) {
        $j('#' + commentsCtrlId + ' ul').prepend(data);
        commentField.val('');
    },
    failure: function () {
        alert("Error adding comment");
    }
});
Run Code Online (Sandbox Code Playgroud)

操作如下所示:

    [HttpPost]
    public ActionResult Create(string commentBody, int parentObjectId, string parentObjectType, int actionId = 0)
    {
        try
        {

        // code to check security and pass info to the database. A comment model object is then passed back to the partial view

            return PartialView("_Comment", comment);
        }
        catch (Exception ex)
        {
            Logger.Instance.LogError("Error in CommentController Create", ex);
            return View("Error");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我可以打破这个方法,并将数据传递到数据库。

我可以在部分视图上断点,这样就可以看到数据正在那里传递,但是当我回到我的 ajax 调用时,它永远不会得到响应(无论是成功还是失败)!我在任何地方都没有收到任何错误,而且绝对没有任何进展。有人对我如何至少尝试调试这里发生的事情有建议吗?

小智 6

您的方法返回一个视图(html),因此您需要将dataType选项更改为'html'

$j.ajax({
    url: url,
    type: "post",
    data: JSON.stringify(commentParam),
    dataType: 'html', // modify
    contentType: "application/json; charset=utf-8",
    success: function (data, status, jqxhr) {
Run Code Online (Sandbox Code Playgroud)

另请注意,您的方法应该PartialViewcatch块中返回 a (就像您对try块所做的那样)

catch (Exception ex)
{
    Logger.Instance.LogError("Error in CommentController Create", ex);
    return PartialView("Error"); // modify
}
Run Code Online (Sandbox Code Playgroud)