Reputation: 3305
I am working in web site don using .net MVC.
In my home page I have area to list some statistics of clients.
Since these values are changing frequently I need to poll data from server and I have planed to use AJAX requests to server continuously after the some interval.
My question is: Is it possible to send list of client object as response to ajax request.
I have a class called Client
and I am looking whether I can send List<Client>
as response)
Can anybody please provide me guide lines or some sample links.
Upvotes: 1
Views: 3634
Reputation: 2201
You need to create a JsonResult method in your controller which returns the list of objects as json and then you can call the method using ajax.
So your method would look something like:
[HttpGet]
public JsonResult GetClients(//any arguments sent from the client here)
{
var clients = //code to get clients
return Json(new {clients = clients}, JsonRequestBehavior.AllowGet);
}
Then make the ajax request in your view using jQuery:
$.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}
});
Upvotes: 3
Reputation: 959
serialize the list to json, This is easier with the json.net library.
at the web page,you can do whatever you would normal operate on json data.
Upvotes: 0
Reputation: 1546
try model:
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; }
}
view:
@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>
Upvotes: 1