這裡是Ajax實際處理介面
<%@ WebHandler Language="C#" Class="ProjectCodeHandler" %>using System;using System.Web;using System.Collections.Generic;using AmpProjectManager.BLL;using AmpProjectManager.Models;public class ProjectCodeHandler : IHttpHandler{ public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string html = ""; //在這裡,參數擷取方式為context.Request.Params["methodType"].ToString() switch (context.Request.Params["methodType"].ToString()) { case "code": html = CodeHandler(context.Request.Params["code"].ToString()); break; case "user": break; } context.Response.Write(html); context.Response.End(); } public bool IsReusable { get { return false; } } public string CodeHandler(string code) { List<string> list = ProjectManager.GetProjectByCode(code);//請將此處理解為:向資料庫請求和以當前參數開頭的所有資料,返回為字串列表 string html = "<ul>"; foreach (string temp in list) { html = html + "<li>" + temp + "</li>"; } html = html + "</ul>"; return html; }}
Html代碼
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>美藥星專案管理系統</title> <script src="JS/jquery-1.8.0.min.js"></script> <script> $(document).ready(function () { //必須要採用Live方法,因為代碼是後來通過別的方法添加入頁面的,不能觸發預先寫好的方法 //li點擊時,將文字框內容改為li的內容 $("li").live("click", function () { $("#txtCode").val($(this).text()); }) //hover效果,因為live是不能綁定hover方法的,變相實現 $("li").live({ mouseenter: function () { $(this).css("background-color", "#39C0FA");//滑鼠移入事件 }, mouseleave: function () { $(this).css("background-color", "white");//滑鼠移出事件 } }); }); //Ajax請求 function SelectTip() { var temp = $("#txtCode").val(); $.ajax({ type: "post",//請求方式:post,get url: "AJAX/ProjectCodeHandler.ashx",//請求的頁面 data: { code: temp, methodType: "code" },//請求參數 //請求成功執行的方法,function內參數名隨意,不影響 success: function (result) { //將Div內原有值清空,將新值賦予DIV內 $(divShowText).html(""); $(divShowText).html(result); }, //請求執行異常執行的方法 error: function (XMLHttpRequest, textStatus, errorThrown) { $(divShowText).html(""); $(divShowText).html("<lable color='red'>異常,請關閉頁面重試,或聯絡管理員</lable>"); } }); } </script> <style> li { text-decoration: none; display: block; border: 1px solid #000; border-bottom: 0.5px solid #000; list-style: none; cursor: pointer; padding: 0px; margin: 0px; } ul { border-bottom: 1px solid #000; display: block; list-style: none; margin: 0px; padding: 0px; } #txtCode { padding: 0px; margin: 0px; } </style></head><body> <form id="form1" runat="server"> <asp:TextBox ID="txtCode" Width="148px" onkeyup="SelectTip()" runat="server"></asp:TextBox><br /> <div id="divShowText" style="width: 150px;"> </div> </form></body></html>
搞了一天,效果如下,輸入任意文字,系統會進資料庫搜尋,點擊所選li,會自動將li內的值填入textBox中。
主要是兩點:第一JQ在頁面上連結進資料庫,這是必須用AJAX的,或者是直接調用頁面存在的方法,因為考慮要轉MVC,所以我就在這裡粘一個連結
http://blog.csdn.net/iouxyz/article/details/5691050
還有就是asp.net怎麼實現ajax,就是.ashx。全稱為:一般程式處理檔案。
結合以上就能實現效果