在Page_Load中asp.net返回数据 [英] asp.net return data in Page_Load

查看:94
本文介绍了在Page_Load中asp.net返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在我的网页请求存在查询字符串参数我想查询在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数据表等)

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];

然后你可以使用第三方库如来创建一个字符串再以JSON数组的presentaion。

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 字符串到响应对象渲染页面的方法。

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.

希望这有助于。

这篇关于在Page_Load中asp.net返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆