微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我在部分剃刀视图上使用$ajax jquery函数获取一个局部视图以及从控制器到页面的强类型模型数据 – >显示在特定的div中.现在,如果有数据模型数据,它可以工作,但如果没有模型数据,我传递json响应,以便我可以检查剃刀视图,以避免空异常.我的问题是$ajax中的方法是不是调用加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);
    });
});

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

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

解决方法:

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

根据官方文件here.

As of 1.9, an empty string returned for JSON data is considered to be
malformed JSON (because it is); this will Now throw an error.

尝试下面的代码而不是使用.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);
    });

因为.done仅在一切正常运行时执行,所以如果出现错误,将不会调用.done.但是无论你的ajax请求是否有效,始终会触发always方法.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐