如何返回带有错误消息的json

时间:2015-01-14 04:42:18

标签: ajax asp.net-mvc json

大家好我使用ajax通过Id调用详细模型。但是如果模型返回数据为空,我想显示一条消息。我怎么样?

我的代码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);
        }
    }

1 个答案:

答案 0 :(得分:2)

如果返回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);
  }
}