将JSON从控制器传递到视图

3

我将尝试从我的控制器将一个JSON列表传递到视图中,但是我似乎缺少了一个关键的部分。以下是控制器的方法:

 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);
        }

这是我想要发送JSON列表的视图中的变量:

var data = [];

有没有关于如何开始的提示?我真的不知道从哪里开始。谢谢!
为了简单起见,假设我在视图中有一个按钮调用 GetList()

编辑: 查询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
                    });

(在这里我应该补充一下,这段代码来自教程:http://www.codeproject.com/Articles/629913/Google-Maps-in-MVC-with-Custom-InfoWindow

首先,请确保您的ID是唯一的。它们现在都显示为1。 - Austin Mullins
抱歉,我复制/粘贴得有些马虎 =) - user2915962
你用来查询“GetList” API 的代码在哪里? - James
请检查编辑,我已经更新。 - user2915962
1个回答

2
假设您使用jQuery和Ajax,那么以下内容适用于您:
$(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) {...});
        });
    });
});

您需要进行适当的调整,但基本上,您正在向控制器发送ajax请求,然后将返回的数据传递到您的data[]变量中。


非常感谢!我相信有了这些信息我一定能让它工作起来。我会再回来接受的!再次感谢! - user2915962
完美运行!谢谢! - user2915962
愉快 - 没问题! - jim tollan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接