5

Hello I have a ajax call:

 $.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)
            }
        }
    })
});

and here's controller method:

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 });
    }

But I'm always getting Internal 500 error. Data is received by method and all calculations are ok. I compose return JSON as in example. Where I made a mistake?

szpic
  • 4,346
  • 15
  • 54
  • 85

1 Answers1

6

By default ASP.NET MVC rejects ajax GET requests, you have to allow it by explicitly setting JsonRequestBehavior to AllowGet:

return Json(new { ok = true, quantity = result.Quantity},
    JsonRequestBehavior.AllowGet);
Zabavsky
  • 13,340
  • 8
  • 54
  • 79