asp.net-mvc - 从 Controller 传递 json 到 View

标签 asp.net-mvc json

我试图将一个 json 列表从我的 Controller 传递到我的 View ,但我遗漏了一大块拼图。这是 Controller 方法:

 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 列表发送到的 View 中的 var:

var data = [];

关于如何进行此操作的任何提示?我真的不知道从哪里开始。谢谢!
为了简单起见,假设我在调用 GetList()

的 View 中有一个按钮

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

最佳答案

假设使用 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) {...});
        });
    });
});

您必须进行调整以适应,但基本上,您是向 Controller 发送一个 ajax 请求,然后将返回的数据传递到您的 data[] 变量中。

关于asp.net-mvc - 从 Controller 传递 json 到 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24885767/

相关文章:

python - Flask 中的 API——返回 JSON 但 HTML 异常破坏了我的 JSON 客户端

json - Odoo : Export res. 公司反对 JSON

c# - 在多个客户端使用它的情况下保护 ASP.NET Web API 2 的最佳方法

sql - Linq 看不到属性

c# - MVC 中下拉列表的 if else 条件

c# - Entity Framework 4.2,无法设置标识插入

来自 Javascript JSONArray 的 Java JSONArray

没有显式登录的 ASP.NET 登录重定向

json - AWS Lambda http请求: Unable to stringify body as json: Converting circular structure to JSON

javascript - 如何将 JSON 对象字符串转换为 Javascript 数组