问题描述
我有这个调用,它调用控制器中的一个动作,并期望在名为 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