Insus.NET的以前的ASP.NET MVC的练习中,也有实现过Autocomplete的功能。依次是使用jQuery来实现。
首先在数据库准备一些数据:
CREATE TABLE [dbo].[Item]Source Code
(
[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
转到ASP.NET MVC项目中,创建一个model:
再创建一个Entity:
创建视图操作Action:
安装jQueryUI:
创建MVC视图:
$(function () {Source Code
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;
}
})
});