从控制器传递json到视图

时间:2014-07-22 11:10:15

标签: asp.net-mvc json

我试图将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:

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

1 个答案:

答案 0 :(得分: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请求,然后将返回的数据传递给你的数据[] var。