ایجاد AutoComplete Textbox در ASP.Net
شنبه 17 آبان 1393در این مقاله سعی داریم تا با یکی از رو ش های AutoComplete Textbox در ASP.NET آشنا شویم
روش های متعددی برای پیاده سازی این موضوع مثل استفاده از کنترل Ajax AutoComplete با
Web Service و WCFدر ASP.NET موجود است.
ولی ما در این مقاله نحوه پیاده سازی را با استفاده از JQery یاد می گیریم.
مراحل:
در ایتدا یک table به نام tblEmp با فیلدهای Id و EmpName در SQL Server ایجاد کنید.
سپس Plugin های زیر را دانلود کنید:
http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js
http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js
http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css"
یک صفحه با کنترل textbox ایجاد کنید و jquery های مورد نیاز را در head صفحه وارد کنید.
متد های jqery را همانند زیر بنویسید.
%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="AjaxTest.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js"></script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
<script type="text/javascript">
$(function () {
$("#txtEmpName").autocomplete({
source: function (request, response) { var param = { empName: $('#txtEmpName').val() };
$.ajax({
url: "WebForm1.aspx/GetEmpNames",
data: JSON.stringify(param),
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var err = eval("(" + XMLHttpRequest.responseText + ")");
alert(err.Message)
// console.log("Ajax Error!");
}
});
},
minLength: 2 //This is the Char length of inputTextBox
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
EmpName : <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>
<br />
<br />
<br />
</div>
</form>
</body>
</html>
در آخر کد های زیر را در code behind وارد کنید:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Services;
namespace AjaxTest
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static List<string> GetEmpNames(string empName)
{
List<string> Emp = new List<string>();
string query = string.Format("SELECT EmpName FROM tblEmp WHERE EmpName LIKE '%{0}%'", empName);
using (SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Emp.Add(reader.GetString(0));
}
}
}
return Emp;
}
}
}
- ASP.net
- 3k بازدید
- 12 تشکر