ASP.NET MVC AJAX 调用控制器不返回任何数据

问题描述

我正在尝试使用 AJAX 调用调用 ASP.NET MVC 控制器。基本上我想根据从下拉列表中选择的 ID 返回客户详细信息。在调试时,控制器被命中并以 JSON 格式返回数据,但是在调试 javascript 时,它永远不会成功、失败或错误

这是我正在使用的代码

查看:

<script type="text/javascript">
    $(document).ready(function () {
        $("#CustomerId").select2({
            placeholder: "Select a customer"
        });

        $("#CustomerId").change(function () {
            var param = $("#CustomerId Option:Selected").val();
           
            $.ajax({
                type: 'GET',data: { Id: param },url: '/QuickInvoices/GetCustDetails',success: {
                    function(response) {
                       
                        if (response != null) {
                            alert("hello");
                            $('customer_CompanyName').val(response.CompanyName);
                        }
                        else {
                            alert("something went wrong!");
                        }
                    }
                },failure: function (response) {
                    alert('Failed');
                },error: function (response) {
                    alert('error' + response.responseText);
                }
            });
        });
    });
</script>

控制器:

[HttpGet]
public JsonResult GetCustDetails(int Id)
{
    Customer customer = db.Customers.Where(x => x.Id == Id)
                                    .SingleOrDefault<Customer>();

    return Json(customer,JsonRequestBehavior.AllowGet);
}

有人可以帮忙吗?

解决方法

请尝试下面的代码示例并检查网络选项卡的请求和响应 你会得到面糊的想法

 $(document).ready(function () {
        $("#CustomerId").select2({
            placeholder: "Select a customer"
        });
        $("#CustomerId").change(function () {
            var param = $("#CustomerId Option:Selected").val();
                   $.ajax({  
                        type: "POST",url: '@Url.Action("GetCustDetails","QuickInvoices")',data: { Id: param },dataType: "json"  
                        contentType: 'application/json; charset=utf-8',success: function(data) {  
                            alert(data.msg);  
                        },error: function() {  
                            alert("Error occured!!")  
                        }  
                    });  
        });
    });