一般處理程序:是一個實現System.Web.IHttpHandler接口的特殊類。任何一個實現了IHttpHandler接口的類,是作為一個外部請求的目標程序的前提:
一般用於和HTML網頁互動
一、需求:根據ID查詢名稱
1、右鍵新建項目 選擇【一般處理程序】后綴名 ashx
2、完成后 再新建 HTML頁面(使用表單提交完成)
代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<form method="post" action="Handler1.ashx">
<div>編號:<input type="text" name="txtCode"/></div>
<div><input type="submit" name="txtId" value="查詢" /></div>
</form>
</body>
</html>
3、【一般處理程序】后台代碼 使用 (Request)關鍵詞語獲取 請求數據
代碼

using System; using System.Collections.Generic; using System.Linq; using System.Web; using Models; using System.Data; using System.Data.SqlClient; namespace WebApplication1 { /// <summary>
/// Handler1 的摘要說明 /// </summary>
public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { //得到html請求Id
string Id = context.Request["txtCode"].ToString(); string sql = $"SELECT * FROM dbo.T_BL_Unit WHERE FClientID='{Id}'"; string UnitName = string.Empty; DataTable dr = DBHelper.Query(sql, null, false); if (dr != null) { UnitName = dr.Rows[0]["UnitName"].ToString(); } context.Response.Write("名稱:" + UnitName); } public bool IsReusable { get { return false; } } } }
顯示結果:
二、使用【ajax】實現【一般處理程序】數據互動(需求:注冊用戶是否存在給予提醒)
1、新建【register.html】頁面,並引起【jQuery】腳本 ;【ajax】常用屬性
代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript" src="js/jquery-1.12.4.js"></script>
<script type="text/javascript"> $(function () { $('#txtAccount').blur(function () { //光標離開事件
$.ajax({ type: 'post', //請求類型
url: 'CheckUser.ashx', //請求后台路徑地址
dataType: 'text', //服務器返回客戶端的數據類型
data: { 'account': $('#txtAccount').val() }, //提交到服務器數據,以json格式傳遞
success: function (msg) { //服務器返回到客戶端結果數據
$("#sp").text(msg); } }); }); }) </script>
</head>
<body>
<div>
<form >
<div> 用戶名:<input id="txtAccount" name="txtAccount" />
<span id="sp"></span>
</div>
<div>密碼:<input type="password" name="txtPassword" /></div>
<div>
<input type="submit" value="注冊" />
</div>
</form>
</div>
</body>
</html>
2、右鍵新建【一般處理程序:CheckUser.ashx】添加 判斷代碼即可
代碼:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using Models; using System.Data; using System.Data.SqlClient; namespace WebApplication1 { /// <summary>
/// CheckUser 的摘要說明 /// </summary>
public class CheckUser : IHttpHandler { public void ProcessRequest(HttpContext context) { string Account = context.Request["account"].ToString(); string sql = $"SELECT * FROM T_Bg_UserInfo WHERE Name='{Account}'"; DataTable dt = DBHelper.Query(sql, null, false); string msg = ""; if (dt.Rows.Count > 0) { msg = "該用戶名已經被注冊"; } else { msg = "可以注冊該用戶名"; } context.Response.Write(msg); } public bool IsReusable { get { return false; } } } }
顯示結果: