Reputation: 2711
Im trying to pass a list of json from my controller to my view but i am missing a big piece of the puzzle. This is the controller method:
public ActionResult GetList()
{
var model = new ViewModel();
model.Places = new List<Place>
{
new Place() {Id = 1, Catch = "Gädda", PlaceName = "Arboga", GeoLat = 59.394861, GeoLong = 15.854361},
new Place() {Id = 2, Catch = "Aborre", PlaceName = "Fis", GeoLat = 59.394861, GeoLong = 15.845361}
};
return Json(model.Places, JsonRequestBehavior.AllowGet);
}
This is the var in the view to which i am trying to send the list of json:
var data = [];
Any tips on how to go about this? I really have no idea where to start. Thanks!
For simplicitys sake, lets say I have a button in the view that calls GetList()
EDIT: The code that querys the API:
// Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
$.each(data, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title': item.PlaceName
});
(At this point I should add that this code comes from a tutorial:) http://www.codeproject.com/Articles/629913/Google-Maps-in-MVC-with-Custom-InfoWindow
Upvotes: 3
Views: 3633
Reputation: 22485
assuming jquery and ajax, then the following would work for you:
$(function(){
$('#yourbuttonid').on('click', function(){
$.ajax({
// in a real scenario, use data-attrs on the html
// rather than linking directly to the url
url: '@Url.Action("GetList", "yourcontroller")',
context: document.body
}).done(function(serverdata) {
data = serverdata;
// as per your edit -now loop round the data var
$.each(data, function (i, item) {...});
});
});
});
you'll have to tweak to suit, but basically, you're sending an ajax request to your controller and then passing the returned data into your data[] var.
Upvotes: 2