【发布时间】:2018-03-10 15:32:00
【问题描述】:
我正在开发一个网页,该网页显示开放的街道地图并通过经纬度坐标从 SQL Server 数据库中获取数据
我使用 asp.net mvc 并给我这个错误
未捕获的类型错误:无法读取未定义的属性“名称”
我在哪里通过 javascript 绑定数据库中的数据
型号
这个模型数据我创建了 GetMap(),它通过 Json 函数从数据库返回数据
[HttpPost]
public JsonResult GetMap()
{
var data1 =(from p in db.Map
select new
{
Name = p.Name,
Latitude = p.Latitude,
Logitude = p.Logitude,
Location = p.Location,
Description = p.Description,
Id = p.Id
}).ToList().Select(res => new Map
{
Name = res.Name,
Latitude = res.Latitude,
Logitude = res.Logitude,
Location = res.Location,
Description = res.Description,
Id = res.Id
});
return Json(data1, JsonRequestBehavior.AllowGet);
}
</pre>
查看文件
查看显示地图并通过 Json 函数返回数据的文件
<div id="mapid" style="height:600px"></div>
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
var map = L.map('mapid').setView([31.291340, 34.244190], 13);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
$.ajax({
type: "POST",
url: '/Maps/GetMap',
success: function (data) {
var result = JSON.stringify(data);
for (var i = 0; i < result.length; ++i) {
var popup =
'<b>Name:</b> ' + data[i].Name +
'<br/><b>Latitude:</b> ' + data[i].Latitude +
'<br/><b>Longitude:</b> ' + data[i].Logitude +
'<br/><b>Location:</b> ' + data[i].Location;
L.marker([data[i].Latitude, data[i].Logitude])
.bindPopup(popup)
.addTo(map);
}
},
error: function (xhr) {
console.log(xhr.responseText);
alert("Error has occurred..");
}
});
});
</script>
【问题讨论】:
-
检查成功函数中的for循环,迭代到
result.length,但result应该是data。错误消息表明某些data[i]未定义。 -
试试 $.parseJSON();还要检查您获得的数据
-
您的 linq 查询中发生了什么?您可以删除
.ToList()之后的Select部分。而且,如果这些是Map对象中的唯一属性,您不妨摆脱整个查询,只做return Json(db.Map.ToList()) -
我的回答对你有用吗?
标签: javascript asp.net asp.net-mvc