简体   繁体   中英

Creating a dynamic JSON from C# to JavaScript

I am new at C# programming and I am developing an application based on geolocation for my Graduate.

I have a Javascript which is responsible for creating the map and inserting the markers. But the markers are inserted from a JSON file, like this:

{
    "Id": 1,
    "Latitude": -19.212355602107472,
    "Longitude": -44.20234468749999,
    "Descricao": "Conteúdo do InfoBox 1"
},

And after that. they call this file by this:

function carregarPontos() {

$.getJSON('js/pontos.json', function(pontos) {

    $.each(pontos, function(index, ponto) {

        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(ponto.Latitude, ponto.Longitude),
            title: "Meu ponto personalizado! :-D",
            map: map
        });

    });

});

}

carregarPontos();

My problem is I need to have those points from MySql DB.

I created a DataTable where I have the information I need to pass to this JSON, but I don't have any clues regarding how to make it.

Any help? Please keep in mind I am a noob at C# and JSON programming.

While the standard C# library offers some JSON support, you're better off using the free JSON.Net library from Newtonsoft. You can add it to your project in Visual Studio through the NuGet package manager ( Project > Manage NuGet packages ).

Then make sure your file has:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

To parse a JSON, just write dynamic json = JObject.Parse(str);
Then you can access its properties just like you would in JavaScript, the only difference being that undefined properties will return null.

dynamic json = JObject.Parse("{example: \"Hello world\"}");
Console.Write(json.example); // prints "Hello world"

To write a JSON, just create a JObject and then append strings, numbers, JArrays and JObjects to it.

dynamic json = new JObject();
json.example = "Hello world";
json.myArray = new JArray(1, 2, 3, 4);
Console.Write(json);
//  {
//    "example": "Hello world",
//    "myArray": [
//      1,
//      2,
//      3,
//      4
//    ]
//  }

as far as I understand you have some data stored in your sql database from where you will fetch the data and pass to a javascript function. If that is the case then you can refer to this link.

Pass json/javascript data/objects to c# function using ajax

The example given is using aspx approach and not the MVC but it will be similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM