Insus.NET的以前的ASP.NET MVC的练习中,也有实现过Autocomplete的功能。依次是使用jQuery来实现。
首先在数据库准备一些数据:
class="code_img_closed" src="/Upload/Images/2016070605/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('d166cc69-ae4b-423b-a3f5-b3cbf1b11759',event)" src="/Upload/Images/2016070605/2B1B950FA3DF188F.gif" alt="" />
CREATE TABLE [dbo].[Item] ( [Item_nbr] INT IDENTITY(1,1) PRIMARY KEY NOT NULL, [ItemName] NVARCHAR(40) ) GO INSERT INTO [dbo].[Item] ( [ItemName] ) VALUES ('Q04-AA-0001'),('Q04-AA-0002'),('Q04-AA-0003'),('Q04-AA-0004'),('Q04-AA-0005'), ('Q04-BB-0001'),('Q04-BB-0002'),('Q04-BB-0003'),('Q04-BB-0004'),('Q04-BB-0005'), ('Q04-CC-0001'),('Q04-CC-0002'),('Q04-CC-0003'),('Q04-CC-0004'),('Q04-CC-0005'), ('Q04-DD-0001'),('Q04-DD-0002'),('Q04-DD-0003'),('Q04-DD-0004'),('Q04-DD-0005'), ('Q04-EE-0001'),('Q04-EE-0002'),('Q04-EE-0003'),('Q04-EE-0004'),('Q04-EE-0005'), ('Q04-FF-0001'),('Q04-FF-0002'),('Q04-FF-0003'),('Q04-FF-0004'),('Q04-FF-0005') GO CREATE PROCEDURE [dbo].[usp_Item_GetAll] AS SELECT [Item_nbr],[ItemName] FROM [dbo].[Item] GOSource Code
转到ASP.NET MVC项目中,创建一个model:
再创建一个Entity:
创建视图操作Action:
安装jQueryUI:
创建MVC视图:
上面标记#3是jQuery代码,详细如下:
$(function () { var cache = {}; $("#itemName").autocomplete({ minLength: 0, source: function (request, response) { var term = request.term; if (term in cache) { data = cache[term]; response($.map(data, function (item) { return { label: item.ItemName, value: item.Item_nbr } })); } else { $.ajax({ url: "/July16/Autocomplete", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify({ top: 10, term: request.term }), success: function (data) { if (data.length) { cache[term] = data ; response($.map(data, function (item) { return { label: item.ItemName, value: item.Item_nbr } })); } } }); } }, focus: function (event, ui) { $("#itemName").val(ui.item.label); return false; }, select: function (event, ui) { $("#itemName").val(ui.item.label); $("#itemNbr-id").val(ui.item.value); return false; } }) });Source Code
实时操作演示: