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

为什么代码总是在将控制权返回给请求时转到非假部分?

如何解决为什么代码总是在将控制权返回给请求时转到非假部分?

我有这个调用,它调用控制器中的一个动作,并期望在名为 data 的对象中为真或假。

$("#btnReview").click(function () {
    var data = {
        'id': '1','recordID': selectedinspectionId,'RoleRemarks': $("#CNGinspectionReport_RoleRemarks").val()
    };

    $.post('/CNGinspectionReport/ChangeStatus',data,function (data) {

        if (data == false) {

            alert('Something went wrong');
        }
        else {
            alert('Record reviewed successfully. Kindly review the further records,if any.');
           
        }
    });
});

public ActionResult ChangeStatus(int id,int recordID,string RoleRemarks,string Role = "") // Later,this should be converted to an object instead of parameters
{
    try
    {

        using (UnitOfWork uwork = new UnitOfWork())
        {
            CNGinspectionReportDAL = new CNGinspectionReportDAL();

            User user = (User)Session["User"];

            CNGinspectionReport CNGinspectionReport = uwork.CNGinspectionReportRepository.GetByID(recordID);

            CNGinspectionReport.CNGinspectionReportID = recordID;

            bool statusCrossOffice = false;

            if (id == 1) //Reviewed
            {
                if(user.Office.Trim() != CNGinspectionReport.StationName.Trim())
                {

                    return Json(new { data = statusCrossOffice,message = "Sorry,this record belongs to another office/station and can only be reviewed by the user of the same station/office" });
                }

                CNGinspectionReport.RoleRemarks = RoleRemarks;

                CNGinspectionReport.CheckedBy = user.UserID;
                CNGinspectionReport.CheckedByName = user.UserName;
                CNGinspectionReport.Status = (byte)id;
                CNGinspectionReport.ReviewDate = DateTime.Now;

            }
            return Json(new { data = status,message = "Success" });
        }
    }
    catch (Exception ex)
    {
        ViewBag.Error = ex.Message;
        return Json(new { data = false,message = ex.Message });
    }
}

但问题是当返回到Ajax调用时,它仍然转到else块。为什么?我已经清楚地在数据中返回了 Fase,但它仍然转到了不是 FALSE 的 else 部分。

解决方法

您应该评估返回对象的数据属性

if (data.data == false) {
         alert('Something went wrong');
}

这是因为 data 返回的值是一个对象而不是布尔值。你可以自己检查这个值:

$.post('/CNGInspectionReport/ChangeStatus',data,function (data) {
         alert(JSON.stringify(data));
         // etc

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