Generic Handler ها که معمولا با فرمت ( ASHX ) شناخته میشوند , Handler هایی برای پردازش درخواست ها , و در صورت نیاز برگشت نتیجه هستند. JSON Generic HTTP Handler یکی نوع از این Generic Handler هاست .بطور مثال : اینگونه فرض کنید که ما با استفاده از AJAX در JQUERY قابل استفاده است از بانک اطلاعاتی خود یکسری رکورد هارا خوانده و در قالب JSON نمایش میدهیم بدون اینکه هیچ رفرشی یا postback در سایت صورت گیرد.
انتظار میرود که تا حدودی با مفهوم Generic و JSON آشنا باشید.
برای شروع کار یک دیتابس به شکل زیر ایجاد میکنیم که شامل جدول customers میباشد:
یک سری اطلاعات پیش فرض در جدول وارد میکنیم:
حالا به پروژه خود یکی Generic Handler اضافه میکنیم که دارای فرمت ASHX میباشد.
Generic Handler
حال میخواهیم که JSON Generic HTTP Handler را درست کنیم که اطلاعات جدول customers را بخواند و در قالب یک فایل JSON نمایش دهد
JSON Generic HTTP Handler از ما ۲ پارامتر را به صورت QueryString میپذیرد
- customerId – که اگر یک مقدار خاص داشته باشد اطلاعات رافقط برای آن مشتری خاص نمایش میدهد.
- callback – این پارامتر مقدار بازگشتی تابع را نگه داری میکند که از سمت کاربر اجرا میشود , زمانی که اطلاعا با استفاده از AJAX یا JQUERY با استفاده از JSON Generic HTTP Handler تقاضا میشود .
کد C# برای این کار به این صورت است :
using System; using System.Web; using System.Data; using System.Configuration; using System.Data.SqlClient; using System.Collections.Generic; using System.Web.Script.Serialization; public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { string callback = context.Request.QueryString["callback"]; int customerId = 0; int.TryParse(context.Request.QueryString["customerId"], out customerId); string json = this.GetCustomersJSON(customerId); if (!string.IsNullOrEmpty(callback)) { json = string.Format("{0}({1});", callback, json); } context.Response.ContentType = "text/json"; context.Response.Write(json); } private string GetCustomersJSON(int customerId) { List<object> customers = new List<object>(); using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "SELECT * FROM Customers WHERE CustomerId = @CustomerId OR @CustomerId = 0"; cmd.Parameters.AddWithValue("@CustomerId", customerId); cmd.Connection = conn; conn.Open(); using (SqlDataReader sdr = cmd.ExecuteReader()) { while (sdr.Read()) { customers.Add(new { CustomerId = sdr["CustomerId"], Name = sdr["Name"], Country = sdr["Country"] }); } } conn.Close(); } return (new JavaScriptSerializer().Serialize(customers)); } } public bool IsReusable { get { return false; } } }
قطعه کد VB.NET برای این کار :
Imports System Imports System.Web Imports System.Data Imports System.Configuration Imports System.Data.SqlClient Imports System.Collections.Generic Imports System.Web.Script.Serialization Public Class Handler : Implements IHttpHandler Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest Dim callback As String = context.Request.QueryString("callback") Dim customerId As Integer = 0 Integer.TryParse(context.Request.QueryString("customerId"), customerId) Dim json As String = Me.GetCustomersJSON(customerId) If Not String.IsNullOrEmpty(callback) Then json = String.Format("{0}({1});", callback, json) End If context.Response.ContentType = "text/json" context.Response.Write(json) End Sub Private Function GetCustomersJSON(customerId As Integer) As String Dim customers As New List(Of Object)() Using conn As New SqlConnection() conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString Using cmd As New SqlCommand() cmd.CommandText = "SELECT * FROM Customers WHERE CustomerId = @CustomerId OR @CustomerId = 0" cmd.Parameters.AddWithValue("@CustomerId", customerId) cmd.Connection = conn conn.Open() Using sdr As SqlDataReader = cmd.ExecuteReader() While sdr.Read() customers.Add(New With { _ .CustomerId = sdr("CustomerId"), _ .Name = sdr("Name"), _ .Country = sdr("Country") _ }) End While End Using conn.Close() End Using Return (New JavaScriptSerializer().Serialize(customers)) End Using End Function Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class
مرحله آخر فراخوانی استفاده از این JSON Generic HTTP Handler است که در سایت نمایش داده شود.
برای این کار یک دکمه یا Button از نوع HTML ( دقت کنید که از نوع دکمه های ASP نباشد) به سایت اضافه میکنیم همچنین یک textbox از نوع html به سایت اضافه میکنیم .
یک جدول هم ایجاد میکنیم که با فراخوانی و اجرای درخواست داده ها در جدول نمایش داده شود .
قطعه کد این قسمت به این صورت میشود :
$(function () { GetCustomers(); $("#btnSearch").click(function () { GetCustomers(); }); }); function GetCustomers() { var table = $("#tblCustomers"); var customerId = $.trim($("#txtCustomerId").val()); $.getJSON('<%=ResolveUrl("~/Handler.ashx")%>' + '?customerId=' + customerId + '&callback=?', function (result) { table.find("tr:not(:first)").remove(); $.each(result, function (i, customer) { var row = table[0].insertRow(-1); $(row).append(" <td /> "); $(row).find("td").eq(0).html(customer.CustomerId); $(row).append(" <td /> "); $(row).find("td").eq(1).html(customer.Name); $(row).append(" <td /> "); $(row).find("td").eq(2).html(customer.Country); }); }); } CustomerId: <input type="text" id="txtCustomerId" /> <input type="button" id="btnSearch" value="Search" /> <hr /> <table id="tblCustomers" border="0" cellpadding="0" cellspacing="0"> <tr> <th style="width: 90px"> Customer Id </th> <th style="width: 120px"> Name </th> <th style="width: 90px"> Country </th> </tr> </table>
هیچ دیدگاهی نوشته نشده است.