Insus.NET的以前的ASP.NET MVC的練習中,也有實現過Autocomplete的功能。依次是使用jQuery來實現。
首先在數據庫准備一些數據:
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] GO Source Code
轉到ASP.NET MVC項目中,創建一個model:
再創建一個Entity:
創建視圖操作Action:
安裝jQueryUI:
創建MVC視圖:
$(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