我正在使用 .net MVC 在网站上工作。
在我的主页上,我有一个区域可以列出一些客户的统计数据。
由于这些值经常变化,我需要从服务器轮询数据,并且我计划在一段时间后连续使用 AJAX 请求服务器。
我的问题是:是否可以发送客户端对象列表作为对 ajax 请求的响应。
我有一门课叫 Client
我正在寻找是否可以发送 List<Client>
作为回应)
谁能给我提供指南或一些示例链接。
最佳答案
您需要在您的 Controller 中创建一个 JsonResult 方法,它将对象列表作为 json 返回,然后您可以使用 ajax 调用该方法。
所以你的方法看起来像这样:
[HttpGet]
public JsonResult GetClients(//any arguments sent from the client here)
{
var clients = //code to get clients
return Json(new {clients = clients}, JsonRequestBehavior.AllowGet);
}
然后使用 jQuery 在您的 View 中发出 ajax 请求:
$.ajax({
url: //url to access GetClients method e.g. '/home/GetClients',
method: 'GET',
data: //any arguments you want to send to the server
success: function(resp){
var clients = resp.clients;//get list of clients from the response
//do stuff with the list of clients
},
error: {//code to handle what happens if an error occurs}
});
关于c# - 如何发送对象列表作为对 ajax 请求的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19394455/