簡體   English   中英

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

[英]$ajax done function is not working in ASP.NET -MVC5 application

我在部分剃刀視圖上使用$ 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。

根據這里的官方文件。

從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);
    });

因為。 只有當一切都成功運行時才執行done所以如果出現錯誤則不會被調用.done將不會被調用。 但是無論你的ajax請求是否有效,始終會觸發always方法。

正確的答案是在控制器動作方法中,修改如下;

 return Json(new { Response = "Provide Your Address Detail!", RecordStatus ="Not Available" }, JsonRequestBehavior.AllowGet);

更改此代碼:

 if (data.itemCount == 0) {
                        $('#row-' + data.deleteId).fadeOut('slow');
                    } else {
                        $('#item-count-' + data.deleteId).text(data.itemCount);
                    }

                    $('#cart-total').text(data.cartTotal);
                    $('#update-message').text(data.message);
                    $('#cart-status').text(data.cartCount);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM