【问题标题】:how to send object list as response to an ajax request如何发送对象列表作为对 ajax 请求的响应
【发布时间】:2013-10-16 15:56:49
【问题描述】:

我正在使用 .net MVC 的网站工作。

在我的主页中,我有一些区域可以列出客户的一些统计数据。
由于这些值经常变化,我需要从服务器轮询数据,并且我计划在一段时间后连续使用 AJAX 请求到服务器。

我的问题是:是否可以发送客户端对象列表作为对 ajax 请求的响应。
我有一个名为Client 的课程,我正在寻找是否可以发送List<Client> 作为回复)

谁能给我一些指导方针或一些示例链接。

【问题讨论】:

  • 你看Json了吗?

标签: c# asp.net-mvc


【解决方案1】:

您需要在控制器中创建一个 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 在您的视图中发出 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}
});

【讨论】:

    【解决方案2】:

    试试 型号:

    public class Car
    {
        public int Id { get; set; }
        public string Manufacturer { get; set; }
        public string Model { get; set; }
        public DateTime Year { get; set; }
        public List<Passanger> Passangers { get; set; }
    }
    
    public class Passanger
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }
    

    查看:

    @model Car
    @using(Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { id = "my-form" }))
    {
        @Html.HiddenFor(x => x.Id)
        @Html.TextBoxFor(x => x.Manufacturer)
        @Html.TextBoxFor(x => x.Model)
        @Html.TextBoxFor(x => x.Year)
    
        for(int i = 0, i < Model.Passangers.Count(), i++)
        {
            @Html.HiddenFor(x => Model.Passangers[i].Id)
            @Html.HiddenFor(x => Model.Passangers[i].Name)
        }
    
        <input type="button" value="Submit" id="form-submit" />
    }
    
    <script type="text/javascript">
        $(document).on('click', '#form-submit', function(){
            $.ajax({
                url: "Car/AddCar",
                type: "POST",
                data: $('form#my-form').serialize(),
                success: function (data)
                {
                    alert(data);
                    // put the data in the container where you have the form.
                }
            });
        });
    </script>
    

    more

    【讨论】:

    • 我需要将对象列表从服务器发送到客户端作为对 ajax 请求的响应。在您的解决方案中,您将序列化表单客户端发送到服务器。
    【解决方案3】:

    将列表序列化为json, 使用 json.net 库更容易。

    http://json.codeplex.com/

    在网页上,你可以对json数据进行正常操作。

    【讨论】:

      猜你喜欢
      • 2015-08-06
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-18
      • 2013-10-02
      • 1970-01-01
      相关资源
      最近更新 更多