控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public JsonResult GetJsonData()
{
var data = new List<threat>();
data.Add(new threat { category_id = 0, threat_id = 0, lat = 12, lng = 12 });
data.Add(new threat { category_id = 0, threat_id = 0, lat = 13, lng = 13 });
data.Add(new threat { category_id = 0, threat_id = 0, lat = 14, lng = 14 });
data.Add(new threat { category_id = 0, threat_id = 0, lat = 15, lng = 15 });
return Json(data, JsonRequestBehavior.AllowGet);
}
}
查看:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var locations = [];
$.getJSON("/Home/GetJsonData", null, function (data) {
locations = data;
});
$("#btnShowData").click(function() {
for(var i =0;i < locations.length;i++){
var location = locations[i];
var message = "Location Lat - " + location.lat + ".Location Lon - " + location.lng;
alert(message);
}
});
});
</script>
<div>
<input type="button" id="btnShowData" value="Show Data" />
</div>
我在上面的示例中使用了一個靜態的List<T>
,所以只需替換該邏輯即可從數據庫返回數據,其餘部分將按原樣工作。不確定您使用的是什麼ORM,但這裏有一個簡單的Entity Framework Database First example