简体   繁体   中英

How to get JSON file from server? (ASP.NET)

I have a simple web application that operates with a set of words using JS. In order to test the main code I just put a needed data in a variable in my script.

CONST WORDS = [
    ["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
    ["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
    ["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]

Now I need to build a database (already done) and get such data from the server. So, the question is how do I acquire JSON file from the server using JS? I know how to make GET requests, but what should I do on the server to make it response? (or may be there is an easier way to get this data in JS, considering that I already got it from DB and can easy display on the webpage). Here is a backend code

namespace LFrench
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
        }
    }
}

You need to make json return type method on serverside. Than call it from your get method and do your method on serverside and fill the List and return that list by converting JSON format.

The thing you need to understand is the flow of your request. if you strictly want to do it in the Page_Loag event then I suppose you will have to make a method in your Javascript that will actually accept your data as parameter and then call the Javascript method from the C# CodeBehind Assuming that the data in the parameter is in JSON format. This method works but is not very efficient.

Other way is, in your JQuery side, you should make an ajax call to a WebMethod of yours in the CodeBehind that will actually send the response in JSON format. This is cleaner way of doing it.

Your JQuery should look like:

$(document).ready(function(){
    $.ajax({
       method: "GET", accept: "application/json; charset=utf-8;",
       url: 'MyPage.aspx/GetDataFromDB', success: function(data){
            console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
       }, fail: function(err){
          console.log(err);
      }
    });
});

And your CodeBehind should look like:

[WebMethod]
public static string GetDataFromDB()
{
    var myData = YourDbCall(); // Some method to retrieve data from database
    var body = new 
    {
        Firstname = myData.Firstname,
        Lastname = myData.Lastname,
        Email = myData.Email,
        // Any Other Information
    };
    var json = JsonConvert.SerializeObject(body);
    return json;

}

EDIT Here is how your Word Set will be sent back as JSON:

[WebMethod]
public static string GetDataFromDB()
{
    List<Words> WordsSet = Words.GetWords("Business");

    return JsonConvert.SerializeObject(WordsSet);

}

Make sure you have installed Newtonsoft.JSON from Nuget Package Manager Console . if not you can Open Package Manager Console and run this command:

PM> Install-Package Newtonsoft.Json

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