使用c#将JSON代码导入Javascript文件
本文关键字:导入 Javascript 文件 代码 JSON 使用 | 更新日期: 2023-09-27 18:04:20
我已经用NuGet包Newtonsoft JsonConvert
生成了一些JSON代码。现在我要将代码导入到javascript文件中,这样我就可以创建谷歌地图了。
我的Json代码是这样的:
[
{
"title": 'Alibaug',
"lat": '18.641400',
"lng": '72.872200',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
},
{
"title": 'Mumbai',
"lat": '18.964700',
"lng": '72.825800',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
},
{
"title": 'Pune',
"lat": '18.523600',
"lng": '73.847800',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
];
我在asp.net表单项目中使用的语言是c#。
也看看我之前的问题:https://stackoverflow.com/questions/31480598/make-routes-on-google-map-in-asp-net-website
有什么办法可以解决我的问题吗?
由于
要做到这一点,要么发出ajax请求,要么在.aspx页面上使用<% %>标记。第二个比较容易:)
的例子:
我有一个方法getMapJson()返回我的Json在我的网页背后的代码。aspx页面。将它设置为静态很重要,否则你将无法从mywebpage。aspx
中调用它。namespace MyApplication
{
public partial class MyWebPage : System.Web.UI.Page
{
public static string getMapJson()
{
//your code
return json;
}
}
}
在my网页。在一个Aspx页面,在脚本中,做这样的事情:
var myJsonVariable = $.parseJSON('<%=MyApplication.MyWebPage.getMapJson()%>');
现在你的Json已经反序列化了,在myJsonVariable中:)
你也可以导入一个静态属性而不是方法,但是你必须设置它的值不迟于Page_Load,因为<% %>里面的东西在每次页面加载时只计算一次,所以它不会改变,除非你重新加载。
如果你正在使用MVC,你可以这样做:
public Coordinates
{
public string Title { get; set; }
public string Lat { get; set; }
public string Lng { get; set; }
public string Description { get; set; }
}
public ActionResult GetCoordinates(){
// get your coordinates
List<Coordinates> coordinates = GetCoordinatesFromDatabase();
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var objectAsJsonString = serializer.Serialize(coordinates );
return Json(objectAsJsonString);
}
然后在javascript中反序列化json:
var coordinates = null;
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
success: function(result){
coordinates = JSON.parse(result);
// operate with your object
}
});
希望对你有帮助。
向asp页面发出ajax请求,呈现JSON。
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/http://api.jquery.com/jquery.getjson/