c# - $ajax 完成功能在 ASP.NET -MVC5 应用程序中不起作用

标签 c# ajax asp.net-mvc jquery-ajaxq

我在部分 Razor View 上使用 $ajax jquery 函数来获取另一个部分 View 以及从 Controller 到页面的强类型模型数据--> 显示在特定的 div 中。现在,如果数据模型数据存在,它就可以工作,但如果没有模型数据,我将传递 json 响应,以便我可以检查 razor View 以避免空异常。我的问题是 $ajax 中的 done 方法没有调用 plus 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

我检查了调试,在 Controller 中调用了 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 方法总是会被触发。

关于c# - $ajax 完成功能在 ASP.NET -MVC5 应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31581677/

相关文章:

javascript - ajax 调用的行为因浏览器而异

javascript - 如何更改ajax结果的自动完成

asp.net - 关闭 Chrome 时停止 Visual Studio 调试器

asp.net-mvc - 是否可以为MVC Razor 布局指定可搜索的位置格式?

asp.net-mvc - 为什么特殊字符撇号和其他字符在 HTMl 文件中显示为这样“,”

c# - 最佳实践 : Convert LINQ Query result to a DataTable without looping

c# - WCF 客户端返回空数组 - XML 响应似乎正常

c# - 无法使用集合初始值设定项初始化类型 "x",因为它未实现 'System.Collections.IEnumerable'

java - 生产力研究资料

javascript - Laravel 通过模态上传图片不起作用