asp.net return data in Page_Load

2019-02-27 17:39发布

If a query string param exists in my page request I want to query the database on the server in the Page_Load and then return the result to the client. I can do the query string param check and query the DB but how do I return the data to the page and on the javascript side how do I access that data?

Ideally I would return JSON of an object structure and it would be returning an array of them.

1条回答
姐就是有狂的资本
2楼-- · 2019-02-27 18:15

Yes, returning JSON would be the best option. I'm not sure how you query your database (Do you use LINQ or ADO.NET DataTables, etc)

If you don't have custom object of type you want to send, I recommend you create one. Then you should get an array of them.

Example:

public class Person {
   string Name { get; set; }
   int Age { get; set; }
}

Person[] pArr = new Person[5];

Then you can use a third party library like this to create an string representaion of that array in JSON.

string json = JsonConvert.SerializeObject(product);

Then you write that json string to the Response object so its sent down to the client, by overriding the Render method of the page.

// Don't expect this code to work as it is, but take this as a guidance
Response.Clear();
Response.Write(json);
Response.Close();

on the client side use jQuery library send a request to page, and process the JSON response for you.

$.getJSON('url', function(data) {
  //process data
});

Here is my suggestion if you don't want to use an AJAX request for this:

Use the objects as you would normally do in the page_load, and convert it to a JSON string as explained above.

Then use ClientScriptManager to create an JavaScript variable on the client side when it loaded.

ClientScript.RegisterClientScriptBlock(typeof(Page), "unique_key", "var myObjectList = " + json, true);

After this when the page loads you will have an variable named "myObjectList" with the list of objects without having to make a different AJAX call.

You can directly refer that variable in your javascript and do necessary processing.

Hope this helps.

查看更多
登录 后发表回答