适用于 ASP.NET 2.0 的简单 JSON 处理程序,用于实现 AJAX 功能






4.44/5 (10投票s)
适用于 ASP.NET 2.0 的简单 JSON 处理程序,用于实现 AJAX 功能
引言
本文档描述了如何使用流行的 JavaScript 库(jQuery)使用最少的代码实现 AJAX 功能,而无需使用 ASP.NET 2.0 AJAX 工具包。由于 ASP.NET 2.0 不支持 JSON,因此如果您想使用 ASP.NET 2.0,这将有所帮助。
此示例包含两个下拉控件,分别用于客户和客户描述。当客户下拉菜单更改时,将加载客户描述,而无需重新加载整个页面。

Using the Code

- 需要将 JQuery 库文件包含到项目中,如上所示。
这些是库文件
- jquery-1.4.1-vsdoc.js,jquery-1.4.1.js
- query-1.4.1.min.js
- jquery-1.5.2.min.js
- jquery-ui-1.8.11.custom.min.js
Sample_ajax.js 文件将使用 JQuery 实现 Ajax。
var ajax = {
setDebugMode: function(){
this.debugMode = true;
},
get: function (requestUrl, data, loaderImageId, onSuccess, onComplete) {
if (loaderImageId) {
$("#" + loaderImageId).css('display', 'inline');
}
var completeFunction = function () {
if (onComplete) {
onComplete();
}
if (loaderImageId) {
$("#" + loaderImageId).css('display', 'none');
}
};
$.ajax({
type: "GET",
url: requestUrl,
data: data,
context: this,
success: function (response) {
onSuccess(response);
completeFunction();
},
error: function (response) {
alert("Ajax Request Failed");
this.showError(response);
completeFunction();
}
});
},
post: function (requestUrl, data, loaderImageId, onSuccess, onComplete) {
if (loaderImageId) {
$("#" + loaderImageId).css('display', 'inline');
}
var completeFunction = function () {
if (onComplete) {
onComplete();
}
if (loaderImageId) {
$("#" + loaderImageId).css('display', 'none');
}
};
$.ajax({
type: "POST",
url: requestUrl,
context: this,
data: data,
success: function (response) {
onSuccess(response);
completeFunction();
},
error: function (response) {
alert("Ajax Request Failed");
this.showError(response);
completeFunction();
}
});
},
showError: function(requestObject){
if (this.debugMode){
alert(requestObject.responseText);
}
}
};
ASPX 页面 (SampleAjax.aspx)
按如下方式包含 JavaScript
<script type="text/javascript"
src='<%= this.ResolveUrl("~/Scripts/jquery-1.5.2.min.js")%>' ></script>
<script type="text/javascript"
src='<%= this.ResolveUrl("~/Scripts/jquery-ui-1.8.11.custom.min.js")%>' ></script>
<script type="text/javascript"
src='<%= this.ResolveUrl("~/Scripts/sample_ajax.js")%>' ></script>
编写 JavaScript 以在客户下拉菜单更改时调用客户描述。
<script type="text/javascript">
<% if (SampleJSONWeb.ConfigurationData.DebugMode){ %>
ajax.setDebugMode();
<%} %>
$(document).ready(function ()
{
$("#<%= customerDropDown.ClientID %>").change(function ()
{
var customerTypeId = $('#<%= customerDropDown.ClientID %>').val();
ajax.get('<%= this.ResolveUrl("~/LoadCustomerDescriptions.ashx")%>',
{ 'customerTypeId': customerTypeId },
'CustomerDescriptionsLoader',
function (response)
{
$('#<%= customerDescriptionDropDown.ClientID %>
option').remove();
for (var i = 0; i < response.Data.length; i++)
{
$('#<%= customerDescriptionDropDown.ClientID %>').
append(getOptionString(response.Data[i]));
}
}
);
});
function getOptionString(dataElement)
{
return "<option value='"+dataElement.Id+"' >"+dataElement.Name+"</option>";
}
});
</script>
LoadCustomerDescriptions.ashx 将由上述 JavaScript 调用。
public class LoadCustomerDescriptions : JsonRequestHandler
{
public override void ProcessRequest(HttpContext context)
{
string customerTypeId = context.Request.QueryString["customerTypeId"].ToString();
//load data
GetData getData = new GetData();
IList<ReferenceData> data = getData.GetCustomerescriptions(customerTypeId);
//Insert an empty row as the first row
data.Insert(0, new ReferenceData(string.Empty, string.Empty));
//return as JSON result
Dictionary<string, string> response = new Dictionary<string, string>();
response.Add("Data", GetJsonCollection<ReferenceData>(data));
SetResponse(context, response);
}
}
上述方法从后端获取数据,并以 JSON 格式发送回去。JSON 处理程序具有以下实现来管理 JSON 数据
using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Reflection;
using System.Web.SessionState;
namespace SampleJSONWeb
{
public abstract class JsonRequestHandler : IHttpHandler, IRequiresSessionState
{
public abstract void ProcessRequest(HttpContext context);
protected void SetResponse(HttpContext context, string jsonResponse)
{
context.Response.Cache.SetExpires(DateTime.Now);
context.Response.ContentType = "application/json";
context.Response.Write(jsonResponse);
context.Response.End();
}
protected void SetResponse(HttpContext context,
Dictionary<string, string> attributes)
{
SetResponse(context, GetJsonObject(attributes));
}
protected void SetResponse<T>(HttpContext context, T obj)
{
SetResponse(context, GetJsonObject<T>(obj));
}
protected T CreateObjectFromRequest<T>(HttpContext context) where T: new()
{
T ob = new T();
PropertyInfo[] properties = typeof(T).GetProperties();
foreach (PropertyInfo property in properties)
{
string value = context.Request.Params[property.Name];
if (value == null)
{
continue;
}
if (property.PropertyType != typeof(string) && value == string.Empty)
{
continue;
}
object convertedValue = Convert.ChangeType(value, property.PropertyType);
if (convertedValue == null)
{
continue;
}
property.SetValue(ob, convertedValue, null);
}
return ob;
}
protected string GetJsonObject(Dictionary<string, string> attributes)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
bool firstTime = true;
foreach (string key in attributes.Keys)
{
if (!firstTime)
{
jsonBuilder.Append(",");
}
string name = key;
object value = attributes[key];
jsonBuilder.Append("\"" + name + "\":" + value.ToString());
firstTime = false;
}
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
protected string GetJsonCollection<T>(IEnumerable<T> collection)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("[");
bool first = true;
foreach (T item in collection)
{
if (!first)
{
jsonBuilder.Append(",");
}
jsonBuilder.Append(GetJsonObject<T>(item));
first = false;
}
jsonBuilder.Append("]");
return jsonBuilder.ToString();
}
protected string GetJsonObject<T>(T obj)
{
PropertyInfo[] properties = typeof(T).GetProperties();
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{");
bool firstTime = true;
foreach (PropertyInfo property in properties)
{
if (!firstTime)
{
jsonBuilder.Append(",");
}
string name = property.Name;
object value = property.GetValue(obj, null);
jsonBuilder.Append("\"" + name + "\":\"" + value.ToString() + "\"");
firstTime = false;
}
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}