【问题标题】:Ajax call with a failed to load resource: the server response with a status 500 (internal server error)加载资源失败的 Ajax 调用:服务器响应状态为 500(内部服务器错误)
【发布时间】:2020-11-16 19:49:32
【问题描述】:

我创建了一个执行 ajax 调用的函数,但在调用它时出现此错误。

Failed to load resource: the server responded with a status of 500 (Internal Server Error) 

这是代码:

 $('#Item').change(function () {
        debugger
        $('#Price').empty();
        $('#Description').empty();
        $('#Quantity').val("");
        $('#Amount').val("");
        $.ajax({
            type: "GET",
            url: "/Payments/GetItemByIdForEdit/",
            datatype: "Json",
            data: { id: $('#Item').val() },
            success: function (data) {
                debugger

                $("#Price").val(data.ItemUnitPrice);
                $("#Description").val(data.itemDescription);
                //$("#productId").text(value.Id);



            }
        });
    });

这是操作代码:

public JsonResult GetItemByIdForEdit(string id)
    {
        if (id != "")
        {
            int productId = Convert.ToInt32(id);
            var product = _unitOfWork.Items.GetItemSingleOrDefault(productId);
            return Json(product, JsonRequestBehavior.AllowGet);
        }
        else
        {
            var product = new Item();
            //product.Description = "";
            //product.UnitPrice = 0.0;
            return Json(product, JsonRequestBehavior.AllowGet);

        }
    }

我看不出问题出在哪里?

你有什么解决办法吗?

谢谢

这是调试器模式的结果:

【问题讨论】:

  • 当您使用浏览器访问该 URL 时会发生什么?
  • 转到此操作public JsonResult GetItemByIdForEdit(string id) 然后在触发此功能后,成功功能不会触发success: function (data) { debugger $("#Price").val(data.ItemUnitPrice); $("#Description").val(data.itemDescription); //$("#productId").text(value.Id); } 并给我该错误
  • 成功函数的主要问题在调用GetItemByIdForEdit后没有触发

标签: c# ajax asp.net-mvc


【解决方案1】:

您正在将空值传递给控制器​​。您必须首先对您的父母进行字符串化。示例:

    var postData = JSON.stringify({
        'id': $('#Item').val()
    });

    $.ajax({
        type: "POST",
        url: "/Payments/GetItemByIdForEdit/",
        datatype: "application/json",
        data: postData,
        success: function (data) {
            debugger

            $("#Price").val(data.ItemUnitPrice);
            $("#Description").val(data.itemDescription);
            //$("#productId").text(value.Id);



        }
    });

在你的方法中你可以直接使用 int

public JsonResult GetItemByIdForEdit(int id)

【讨论】:

  • 还是同样的问题,在这个方法public JsonResult GetItemByIdForEdit(int id)id在尝试你的解决方案后为空
  • 确定您的商品有价值吗?例如通过 console.log($('#Item').val()) 记录它
  • 检查我的回答你有错误的 jquery 代码。 Postdata 不是其变量的参数。
猜你喜欢
  • 2015-12-19
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 2014-11-24
  • 2021-07-27
  • 1970-01-01
相关资源
最近更新 更多