c# - 如何发送对象列表作为对 ajax 请求的响应

标签 c# asp.net-mvc

我正在使用 .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/

相关文章:

c# - ASP.NET MVC 3 - 区域路由的边缘案例

.net - 使用 ASP.NET MVC 框架的经验

asp.net-mvc - 将现有的 ASP.NET MVC 网站移植到 DNX

asp.net-mvc - 如何将带连字符和冒号的属性添加到 Razor 中的 Html Helper 方法? (vuejs 语法)

asp.net-mvc - ASP.NET MVC 应用程序中丰富的 UI 可用的最佳选项是什么?

c# - 在 C# 中,如何在不知道其类型的情况下向下转换先前向上转换的对象?

c# - 如何使用 WinDBG 列出所有托管线程的调用堆栈?

c# - 如何推迟执行直到某些事件发生?

c# - 为什么这个看似简单的 Xpath 导航不起作用?

.Net Twitter OAuth 如何执行成功的 GET 请求