这里是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" οnkeyup="SelectTip()" runat="server"></asp:TextBox><br />
<div id="divShowText" style="width: 150px;">
</div>
</form>
</body>
</html>
搞了一天,效果如下,输入任意文字,系统会进数据库搜索,点击所选li,会自动将li内的值填入textBox中。
主要是两点:第一JQ在页面上链接进数据库,这是必须用AJAX的,或者是直接调用页面存在的方法,因为考虑要转MVC,所以我就在这里粘一个链接
http://blog.youkuaiyun.com/iouxyz/article/details/5691050
还有就是asp.net怎么实现ajax,就是.ashx。全称为:一般程序处理文件。
结合以上就能实现效果