پیاده سازی AutoComplete با استفاده از Ajax و Jquery
یکشنبه 3 اسفند 1393در این مقاله میخواهیم با استفاده از Ajax و Jquery در Asp.net به ساخت AutoComplete بپردازیم
در ابتدا به صفحه html خود میپردازیم در این صفحه نیاز به یک کنترل TextBox داریم که باید خصوصیت autocomplete را off مقدار دهی شود زمانی که این مقدار on باشد مرورگر به صورت خودکار این عمل را بر اساس مقادیری که کاربر قبلا وارد کرده است انجام خواهد داد بهمین علت ما این مقدار را روی off قرار میدهیم
برای نمایش داده ها که از طریق autocomplete فراخوانی شده اند از یک لیست استفاده میکینم:
<div> <asp:TextBox runat="server" ClientIDMode="Static" ID="txtCustomer" list="CustomerList" Style="height: 25px; width: 264px;" autocomplete="off" /> <ul class="autocomplete autocomplete1" id="ddlItem"> </ul> </div>
سپس یک تابع برای فراخوانی داده ها به نام GetData مینویسیم که از صفت [Web Method] در بالای متد خود برای ارتباط بین ui و کد سمت سرور استفاده میکنیم که از این طریق متد توسط client اجرا خواهد شد و تابع باد به صورت public و static تعریف شود :
[WebMethod] public static string GetData()//method that is called in the Ajax returns JSON String { DataTable dt = new DataTable(); dt.Columns.Add("Name"); dt.Rows.Add("Ajith"); dt.Rows.Add("Arun"); dt.Rows.Add("Suraj"); dt.Rows.Add("Pankaj"); dt.Rows.Add("Yogesh"); return ConvertDataTabletoString(dt); } public static string ConvertDataTabletoString(DataTable dt) //Function Used to convert DataTable to Json String { System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); Dictionary<string, object> row; foreach (DataRow dr in dt.Rows) { row = new Dictionary<string, object>(); foreach (DataColumn col in dt.Columns) { row.Add(col.ColumnName, dr[col]); } rows.Add(row); } return serializer.Serialize(rows); }
حال از طریق ajax به فراخوانی[WebMethod] میپردازیم کد ajax را با استفاده از json خواهیم نوشت
و مقدار بازگشتی در دوحالت موفقیت آمیز بودن عملیات و یا شکست برسسی میشود و در صورت شکست پیام داده میشود و در صورت موفقیت آمیز بودن یک تابع به نام BindCustomerData فراخوانی میشود که این تابع وظیفه اضافه کردن نتیج به ul یا همون لیست می باشد:
$.ajax({ type: "POST",//Post Method url: 'Default.aspx/GetData',//URL data: '{}', async: false,//synchronous Call contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { //callback function on Success BindCustomerData(response.d); }, failure: function (response) { alert(response.d); //alerts on failure } });
میخواهیم متن یا کامه مورد جستجو رنگ آنرا متمایز نماییم برای تحقق این امر از یک Plugin به نام jQuery.highlight.js به شکل زیر استفاده میکنیم:
$(this).unhighlight();//To unhighlight $(this).highlight($('#txtCustomer').val());//To highlight the text that is being typed
کد به صورت کامل :
$(document).ready(function (jQuery) { $.ajax({ type: "POST",//Post Method url: 'Default.aspx/GetData',//URL data: '{}', async: false,//synchronous Call contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { BindCustomerData(response.d); }, failure: function (response) { alert(response.d); } }); $('#txtCustomer').keyup(function () { if ($(this).val() == '') { $("#ddlItem > li").hide(); // Hides all <li> if the input text is blank BindCustomerData(); } else { var filter = $(this).val(); //gets value of the textbox in var filter //now using .each() we search for text in <li> matching text in var filter $("#ddlItem li").each(function () { //the .search() is a javascript function which returns the postion where the match is found //the new RegExp(filter, "i") is a Regular Expression Filter which helps in filtering text on the //bases of the match found in var filter and the <li> //The "i" in RegExp(filter, "i") denotes that the filter is case-insensitve (won't check the case of text) //you could also use "gi" which perform a global match (find all matches rather than stopping after the first match) //So if the search find a match it will return value greater than -1 if ($(this).text().search(new RegExp(filter, "gi")) < 0) { $(this).hide();//Hides the <li> } else { $(this).show();//Shows the <li> $(this).unhighlight();//Initally unhighlight $(this).highlight($('#txtCustomer').val());//To highlight the text that is being typed } }); } }); }); function BindCustomerData(data) { var ddl = $('#ddlItem').get(0);//Get HTML Element <ul> with ID ddlItem data = JSON.parse(data); //parse Data string into Json ddl.innerHTML = ""; //Removes all <li> in <ul> var opt = ""; for (var i = 0; i < data.length; i++) { opt += "<li onclick='javascript:SelectEvent(\"" + data[i].Name + "\");' >" + data[i].Name + "</li>"; //Create <li> to be added in <ul> } ddl.innerHTML = opt; } //this function is invoked when a particular <li> is clicked function SelectEvent(name) { //the function accepts the value to be add to the textbox in its parameter $('#txtCustomer').val(name); $("#ddlItem > li").hide();//once the value of the textbox is changed all <li>'s are hidden }
حالا میتونید برنامه رو اجرا کنید:
- ASP.net
- 2k بازدید
- 5 تشکر