这次以项目清单作範例
原理
在专案内新增一个.ashx的档案,并且将它CodeBehid连结到后端的.cs,透过前端的ajax呼叫这支.ashx,它会连结到后端的那支.cs,以此连结。
PS:.ashx就是没有前端UI功能的页面,但是可以操作.cs后端的code。
前端:
用ajax将后端取到的资料,用JQ直接append到画面上,达到画面不会reflash。
$.ajax({ url: Test.ashx, type: "post", data: { method: "getcodeitem" }, success: function (e) { var jsonObj = $.parseJSON(e); var $Item = $("#List"); $Item.empty(); $(jsonObj).each(function (index, item) { $Item.append("<option value='" + item.VALUE + "'>" + item.NAME + "</option>"); }); }, error: function (e) { alert(e); } });
后端:
Test.ashx先将编辑器自动帮你生产的code给删掉,只留上面那段code,并在CodeBehind连结到后端的.cs。
<%@ WebHandler Language="C#" Class="GetCodeList" CodeBehind="~/App_Code/GetCodeList.cs" %>
GetCodeList.cs这边先继承IHttpHandler
,并实作IsReusable
和ProcessRequest
这两支method,之后就是去DB捞资料的语法。
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Data.SqlClient;using System.Configuration;using System.Data;using Newtonsoft.Json;public class GetCodeList : IHttpHandler{ public void ProcessRequest(HttpContext context) { string aMethod = context.Request.QueryString["method"].ToString(); if(aMethod == "getcodeitem") { DataTable aDataTable = new DataTable(); using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ToString())) { conn.Open(); SqlCommand cmd = new SqlCommand(@SQL语法, conn); using (SqlDataReader dr = cmd.ExecuteReader()) { try { aDataTable.Load(dr); } finally { conn.Close(); conn.Dispose(); dr.Close(); } } } context.Response.Write(JsonConvert.SerializeObject(aDataTable)); } } public bool IsReusable { get { return false; } }}
这种写法称为泛型处理常式
,是用来处理HTTP Request
的一种方式,可以把ashx想像成没有画面的aspx。