我如何 return json 显示错误消息

How do I return json with error message

大家好我正在使用 ajax 通过 Id 调用细节模型。但是如果模型 return 数据为空,我想显示一条消息。我该怎么办?

我的代码ajax显示细节模型

$('#PGId').blur(function () {
        var errormsg = "";
        var id = $('#PGId').val();
        $.ajax({
            type: "GET",
            url: '@Url.Action("GetDetailPG", "TimeSheetHeader")',
            data: { pgId: id },
            dataType: "json",
            success: function (data) {
               success: function (data) {
                if (data.isValid) {
                    $("#FullName").text(data.FisrtName + " " + data.LastName)
                    $('.Shiff[value="' + data.ShiffId + '"]').prop('checked', true)
                }
                else {
                    alert(data.error);
                }
            },
            },
            error: function () {

            }
        });
    })

我的控制器绑定数据

[HttpGet]
    public ActionResult GetDetailPG(string pgId)
    {
        PGProfileViewModel pgProfileModel = new PGProfileViewModel();
        pgProfileModel.PGId = pgId;
        var query = _pgProfileService.GetPGProfileById(pgProfileModel.PGId);
        var model = query.ToViewModel();

        if (model == null)
        {
            return Json(new {isValid = false, error = "Error Message"}, JsonRequestBehavior.AllowGet);
        }
        else
        {
            model.LastName = query.LastName.Trim();
            model.FisrtName = query.FisrtName.Trim();
            model.ShiffId = query.ShiffId;
            return Json(new { model = model , isValid = true }, JsonRequestBehavior.AllowGet);
        }
    }

如果您 returns 一个 json 对象(作为业务模型错误),javascript data 值(具有请求结果)永远不会为空。

您可以尝试这样的方法:

C#

[HttpGet]
public ActionResult GetDetailPG(string pgId)
{
  PGProfileViewModel pgProfileModel = new PGProfileViewModel();
  pgProfileModel.PGId = pgId;
  var query = _pgProfileService.GetPGProfileById(pgProfileModel.PGId);
  var model = query.ToViewModel();

  if (model == null)
  {
    return Json({
      isValid: false,
      error: "Your error message"
    }, JsonRequestBehavior.AllowGet);
  }
  else
  {
    model.LastName = query.LastName.Trim();
    model.FisrtName = query.FisrtName.Trim();
    model.ShiffId = query.ShiffId;

    return Json({
      model: model,
      isValid: true
      }, JsonRequestBehavior.AllowGet);
   }
}

JS

//success function of your ajax request.
success: function (data) {
  if (data.isValid) {
    $("#FullName").text(data.FisrtName + " " + data.LastName)
    $('.Shiff[value="' + data.ShiffId + '"]').prop('checked', true)
  }
  else {
    alert(data.error);
  }
}