【发布时间】:2021-01-12 21:26:45
【问题描述】:
我正在尝试使用 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);
}
有人可以帮忙吗?
【问题讨论】:
-
浏览器的控制台或网络工具中是否有任何错误?
-
不调试的时候url不一样吗?
-
控制台/网络工具中没有错误,因为我什至尝试在 chrome 上进行调试。调试和发布模式下的url是一样的
-
如@Amit Sakare 在下面的响应中提到的,在“成功”事件之后删除多余的范围定义。我尝试通过删除讨论中多余的花括号来运行您的代码,并且效果很好。
标签: c# jquery ajax asp.net-mvc