我试图将一个 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()
编辑: 查询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/