$ajax done 函数在 ASP.NET -MVC5 应用程序中不起作用

Tox*_*xic 5 c# ajax asp.net-mvc jquery-ajaxq

我在部分剃刀视图上使用 $ajax jquery 函数来获取另一个部分视图以及从控制器到页面的强类型模型数据--> 在特定 div 中显示。现在,如果数据模型数据在那里,它可以工作,但如果没有模型数据,我将传递 json 响应,以便我可以检查 razor 视图以避免空异常。我的问题是 $ajax 中的 done 方法没有调用加上 json 响应,我不知道我哪里做错了

Ajax 函数

$(document).ready(function () {

    /*Address*/
    $.ajax({
        url: '@Url.Action("DisplayStudentAddress")',
        type: "GET",
        cache: false
    }).done(function (data, textStatus, jqXHR) {

        alert(data.Response);

       $('#studentAddressDisplay').html(data);

    }).fail(function (jqXHR, textStatus, errorThrown) {

        alert(jqXHR +"    "+textStatus+"    "+errorThrown);
    });
});
Run Code Online (Sandbox Code Playgroud)

ActionResult 方法

 [HttpGet]
 [Authorize]
 public ActionResult DisplayStudentAddress()
    {
        int _studentEntityID = 0;

        _studentEntityID = _studentProfileServices.GetStudentIDByIdentityUserID(User.Identity.GetUserId());

        Address _studentAddressModel = new Address();

        _studentAddressModel = _studentProfileServices.GetStudentAddressByStudentID(_studentEntityID);


        if (_studentAddressModel != null)
        {
            return PartialView("DisplayStudentAddress_Partial", _studentAddressModel);
        }
        else
        {
             return Json(new { Response = "Provide Your Address Detail!" });
        }
    }
    #endregion
Run Code Online (Sandbox Code Playgroud)

我已经检查调试,json 在控制器中被调用,但它在 ajax 中警告错误

Nee*_*eel 3

如果您的服务器返回 json 响应的空字符串,jQuery 会将其视为失败。空字符串被认为是无效的 json。

根据此处的官方文件。

从 1.9 开始,为 JSON 数据返回的空字符串被视为格式错误的 JSON(因为确实如此);这现在会抛出一个错误。

尝试使用以下代码代替.always:-

$.ajax({
        url: '@Url.Action("DisplayStudentAddress")',
        type: "GET",
        cache: false
    }).always(function (data, textStatus, jqXHR) {

    alert(data.Response);

   $('#studentAddressDisplay').html(data);

}).fail(function (jqXHR, textStatus, errorThrown) {

        alert(jqXHR +"    "+textStatus+"    "+errorThrown);
    });
Run Code Online (Sandbox Code Playgroud)

因为 。done仅当一切成功时才执行,因此如果出现问题.done将不会被调用。但always无论你的 ajax 请求是否有效,该方法总是会被触发。