在C#中通过AJAX从服务器返回数据
问题描述:
我正在使用AJAX调用来显示基于用C#编写的某些逻辑的成功或失败的信息。我现在需要从服务器返回附加数据并显示它。我需要的数据包含在employers
和agencies
变量中。如何将return Json
声明中的数据与success
一起退回?在C#中通过AJAX从服务器返回数据
$.ajax({
url: rootpath + "/clients/hasDuplicateTaxId",
type: "GET",
success: function (data) {
if (data.success) {
// success
}
else {
// fail
}
},
error: function (response) {
var error = response;
}
});
if (taxIdExists)
{
var employers = _employerRepository.GetByTaxId(taxId).ToList();
var agencies = _employerRepository.GetByTaxId(taxId).Select(e => e.GeneralAgency).ToArray();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = false, error = "Error" }, JsonRequestBehavior.AllowGet);
答
您需要的employers
和agencies
变量添加到您提供给Json
匿名类型,像这样:
if (taxIdExists)
{
var employers = _employerRepository.GetByTaxId(taxId).ToList();
var agencies = _employerRepository.GetByTaxId(taxId).Select(e => e.GeneralAgency).ToArray();
return Json(new { success = true, employers, agencies }, JsonRequestBehavior.AllowGet);
}
从那里,你可以访问存储在这些属性的阵列success
$.ajax
处理者电话:
success: function (data) {
if (data.success) {
console.log(data.employers);
console.log(data.agencies);
}
else {
// fail
}
},
它们将是数组,因此您需要遍历它们以提取所需的信息。
将'employers'和'agencies'变量添加到您提供给Json响应的匿名类型。然后可以访问它们在JavaScript的'data'变量中公开的属性/对象/数组。你不可能给你更具体的东西,因为你没有向我们展示这些类实际上是什么样的。 –
看看你用C#代码中的'error'成员做了什么?对其他人也做同样的事情。 –
那会怎样?像这样? return Json(new {success = true,employers = employer,agencies = agencies},JsonRequestBehavior.AllowGet); – noclist