ASP. net mvc implements Autocomplete and jqueryautocomplete using jQuery
In the previous ASP. net mvc exercises of Insus. NET, Autocomplete is also implemented. JQuery is used in sequence.
First, prepare some data in the database:
Create table [dbo]. [Item] ([Item_nbr] int identity (1, 1) primary key not null, [ItemName] NVARCHAR (40) goinsert 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') gocreate procedure [dbo]. [usp_Item_GetAll] ASSELECT [Item_nbr], [ItemName] FROM [dbo]. [Item] GOSource Code
Go to the ASP. net mvc project and create a model:
Create another Entity:
Create view operation Action:
Install jQueryUI:
Create an MVC View:
The above mark #3 is jQuery code, detailed as follows:
$ (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
Real-time operation Demonstration: