从page_load方法中检索JSON

时间:2015-10-25 03:08:48

标签: asp.net json vb.net webforms

我在page_load下运行了两个方法:CreateTables()和GetTables()。 GetTables()返回一个数据集,我想检索该数据集并在我的网页上填充一个表。

这是VB.NET代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    dbConnection = String.Format("Data Source={0}", file)
    CreateTables()
    GetTables()
End Sub

如何检索该数据集?

1 个答案:

答案 0 :(得分:1)

要在网络表单应用程序中获取JSON,最好实现自定义解决方案,而不是使用标准Page life Cycle。这样你就可以更好地控制在任何你想要的地方发送JSON的方式。您可以使用HttpHandler Page方法或Web服务。我建议使用HttpHandlers:

  1. 创建自定义HTTPHandler(* .ashx)。在ProcessRequest方法中处理您的请求。此方法必须从Request获取数据,处理它并将json写入HTTP Response:

    using System.Web.Script.Serialization;
    
     namespace WebApplication2
     {
        public class JSONHandler : IHttpHandler
        {
           public bool IsReusable
           {
              return false;
           }
    
           public void ProcessRequest(HttpContext context)
           {
              string name = (string)context.Request["Name"];
    
              var obj = new { Error = false, Name= name };
              JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
              string result = javaScriptSerializer.Serialize(obj);
    
              context.Response.ContentType = "application/json";
              context.Response.ContentEncoding = Encoding.UTF8;
              context.Response.Write(result);
            }
          }
        }
    
  2. 使用jQuery.Ajax调用此处理程序。您必须定位 .ashx

      function GetData() {
         $.ajax({
         url: "JSONHandler.ashx",
         contentType: "application/json; charset=utf-8",
         data: { 'Name': 'Joseph'},
         success: function(data){
           if(!data.Error){
              var name = data.Name;
              alert(name)
            }
          },
          return false;
        }
    
相关问题