问题描述
如果我的页面请求中存在查询字符串参数,我想在 Page_Load 中查询服务器上的数据库,然后将结果返回给客户端.我可以执行查询字符串参数检查并查询数据库,但如何将数据返回到页面以及在 javascript 端如何访问该数据?
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?
理想情况下,我会返回一个对象结构的 JSON,它会返回一个数组.
Ideally I would return JSON of an object structure and it would be returning an array of them.
推荐答案
是的,返回 JSON 将是最好的选择.我不确定您如何查询数据库(您使用 LINQ 还是 ADO.NET DataTables 等)
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.
示例:
public class Person {
string Name { get; set; }
int Age { get; set; }
}
Person[] pArr = new Person[5];
然后你可以使用像this这样的第三方库来创建一个字符串该数组在 JSON 中的表示.
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);
然后您将该 json
字符串写入 Response 对象,以便通过覆盖页面的 Render 方法将其发送到客户端.
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();
在客户端使用 jQuery 库向页面发送请求,并为您处理 JSON 响应.
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
});
如果您不想为此使用 AJAX 请求,这是我的建议:
Here is my suggestion if you don't want to use an AJAX request for this:
像往常一样在 page_load 中使用对象,并将其转换为 JSON 字符串,如上所述.
Use the objects as you would normally do in the page_load, and convert it to a JSON string as explained above.
然后使用 ClientScriptManager 在客户端加载时创建一个 JavaScript 变量.
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);
在此之后,当页面加载时,您将拥有一个名为myObjectList"的变量,其中包含对象列表,而无需进行不同的 AJAX 调用.
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.
您可以直接在 JavaScript 中引用该变量并进行必要的处理.
You can directly refer that variable in your javascript and do necessary processing.
希望这会有所帮助.
这篇关于asp.net 在 Page_Load 中返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!