2016-01-22 46 views
2

我正在使用AJAX调用来显示基于用C#编写的某些逻辑的成功或失败的信息。我现在需要从服务器返回附加数据并显示它。我需要的数据包含在employersagencies变量中。如何将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); 
+2

将'employers'和'agencies'变量添加到您提供给Json响应的匿名类型。然后可以访问它们在JavaScript的'data'变量中公开的属性/对象/数组。你不可能给你更具体的东西,因为你没有向我们展示这些类实际上是什么样的。 –

+2

看看你用C#代码中的'error'成员做了什么?对其他人也做同样的事情。 –

+0

那会怎样?像这样? return Json(new {success = true,employers = employer,agencies = agencies},JsonRequestBehavior.AllowGet); – noclist

回答

1

您需要的employersagencies变量添加到您提供给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 
    } 
}, 

它们将是数组,因此您需要遍历它们以提取所需的信息。

+0

在将这些变量添加到我的匿名类型后,我放入了我的Ajax请求的错误设置。 – noclist

+0

你得到的错误是什么?您可以设置断点来查找它,或者在控制台中检查请求的状态。 –

+0

我设置了一个断点,它碰到'error:function(response)'的内部。我怎么知道错误是什么? – noclist