一时兴起用Ajax配合JavaScript写实现自动补全功能的TextBox
需要实现的功能
1:该控件可以从数据库中读取数据
2:该控件应该在用户更改TextBox中内容时使用Ajax向服务请求相应数据
3:使用Javascript控制从服务请求到的数据的展现方式
4:使用Javascript注册相关事件
嗯 基本功能就是这样了! 那就开始吧!
启动SQL2008与VS2010后查看了一下可用资源,嗯 还不错数据库中有一个包括全国500多个城市的表(表名:Macaco.CityCollection),这张表有三个字段第一个是AutoID 不用说肯定是自动编号列,第二个是EndNumber 嗯这个比较历害!我也不知道是干什么的 跳过!第三个字段是City里面是城市名。
VS2010打开后加载了一下我的Demo工程 首先在Tools类库项目下添加了一个数据库表对象属性模型类,其次添加了一个数据库表数据访问类。
代码如下:
数据表对象属性模型类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Macaco.Demo.Tools
{
public class CityModel
{
public int ID { get; set; }
public int EndNumber { get; set; }
public string City { get; set; }
}
}数据表数据访问类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace Macaco.Demo.Tools
{
public class CityCollectionTools
{
//以下为从数据库中获取城市信息的数据访问方法
string strcon = "server=.;uid=DemoUser;pwd=DemoUser;DataBase=MacacoOnline;";
public List<CityModel> GetCityDataByEndNumberAndCity(string sqlPar)
{
List<CityModel> cityList = null;
if (string.IsNullOrEmpty(sqlPar))
return cityList;
//此处我们以模糊查询的方法查询前10条符合条件的记录 此处以ID排序实际应用中应该要有一个优先级的字段并以此字段排序
string strcmd = "select top 10 ID,EndNumber,City from Macaco.CityCollection where EndNumber like '%'+@SqlPar+'%' or City like '%'+@SqlPar+'%' order by ID";
SqlCommand sqlcmd = new SqlCommand(strcmd, new SqlConnection(strcon));
sqlcmd.Parameters.Add(new SqlParameter("@SqlPar", SqlDbType.VarChar, 20)).Value = sqlPar;
SqlDataReader sdr = null;
try
{
sqlcmd.Connection.Open();