使用Ajax时,服务器响应状态为500(内部服务器错误)

时间:2014-05-23 10:18:21

标签: ajax asp.net-mvc json

您好,我有一个ajax调用:

 $.ajax({
        url: "/Orders/CheckIfExists",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        data: {
            catalogNumber: viewModel.catalogNumber,
            quantity: viewModel.quantity
        },
        error: function (data) {
            alert("wystąpił nieokreślony błąd " + data);
        },
        success: function (data) {
            if(data.ok)
            {
                alert(data.quantity)
            }
        }
    })
});

以及这里的控制器方法:

public JsonResult CheckIfExists(string catalogNumber, int quantity)
    {
        List<Expression<Func<DeviceInstance, bool>>> where = new List<Expression<Func<DeviceInstance, bool>>>();
        where.Add(w=>w.DeviceUsage.UserId==1);
        where.Add(w => w.Project == null);
        where.Add(w => w.Device.CatalogNo == catalogNumber);
        var result = unitOfWork.deviceInstanceRepository.Get(where)
          .GroupBy(w => new
          {
              DeviceId = w.DeviceId,
              CatalogName = w.Device.CatalogNo,
          })
          .Select(s => new
          {
              Quantity = s.Sum(x => x.Quantity),
          }).First();
        if (result.Quantity >= quantity)
        {
            return Json(new { ok = true, quantity = result.Quantity});

        }
        return Json(new { ok = false });
    }

但我总是得到内部500错误。 通过方法接收数据,所有计算都可以。我在例子中编写了返回JSON。 我犯了什么错误?

1 个答案:

答案 0 :(得分:6)

默认情况下,ASP.NET MVC拒绝ajax GET请求,您必须通过明确将JsonRequestBehavior设置为AllowGet来允许它:

return Json(new { ok = true, quantity = result.Quantity},
    JsonRequestBehavior.AllowGet);