2013-10-16 86 views
1

我在網站中工作不使用.net MVC如何發送對象列表作爲對ajax請求的響應

在我的主頁我有地區列出一些客戶的統計數據。
由於這些值經常更改,我需要從服務器輪詢數據,並且我計劃在某個時間間隔之後連續使用AJAX服務器的請求。

我的問題是:是否有可能發送客戶端對象的列表作爲對ajax請求的響應。
我有一個名爲Client類,我期待我是否可以發送List<Client>爲響應)

可有人請我提供指導線或一些示例鏈接。

+0

你看Json的? – spender

回答

3

您需要在控制器中創建一個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} 
}); 
1

嘗試 型號:

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

+0

我需要從服務器傳輸對象列表作爲對ajax請求的響應。在您的解決方案中,您將發送序列化表單客戶端到服務器。 –

相關問題