asp. net+ajax+sqlserver Automatic completion function realizes parsing

  • 2020-11-25 07:13:51
  • OfStack

The code download

Note: The database connection string is in the web.config file. For ease of operation, the official Northwind database is used.

Reference (tribute to its author) :

² http://www.loveweb8.com/plus/demo.php? aid=57 this example is the html source code. jquery. autocomplete plugin is used to realize the automatic completion function. Because my need is to combine sqlserver database tables to achieve automatic completion. The next step is to turn the database table into an js array, which comes naturally to ajax.

² The two basic development patterns of ES28en.NetAjax Part 2 of this article is to say: an example of js calling webservice.

Code parsing.

1. Add webservice file.

Add a new item -- "WCF Services with AJAX enabled" name the new file DBService.svc.

2. Add a function to ES45en.svc. The return value of the function is the data prompted for completion.
 
[OperationContract] 
public string getSortList() 
{ 
List<string> sorts = new List<string>(); 
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["zhui.pc"].ConnectionString)) 
{ 
cn.Open(); 
SqlCommand cmd = new SqlCommand("select [LastName] from [dbo].[Employees]", cn); 
DataTable dt = new DataTable(); 
using (SqlDataAdapter da = new SqlDataAdapter(cmd)) 
{ 
da.Fill(dt); 
} 

foreach (DataRow row in dt.Rows) 
{ 
sorts.Add(row[0].ToString()); 
} 

cn.Close(); 
} 
return string.Join(",", sorts.ToArray()); 
} 

3. Add js and css to default.aspx file:
 
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> 
<script src="Scripts/jquery.autocomplete.min.js" type="text/javascript"></script> 
<link href="Styles/jquery.autocomplete.css" rel="stylesheet" type="text/css" /> 

4. Call webservice in the head part of ES57en.aspx ($().ready (function ()) function to get the auto-complete data and associate the data into the input field.
 
<script type="text/javascript"> 
$().ready(function () { 

NewsSort.getSortList(OnComplete, OnFailed, null); 

function OnComplete(args, context) { 
$('#MainContent_searchBox').AutoComplete({ 
'data': args.split(","), 
'itemHeight': 20, 
'listDirection': 'down', 
'width': 280 
}).AutoComplete('show'); 
} 

function OnFailed(args) { 
alert(" Make a mistake! "); 
} 
}); 
</script> 

5. Finish.

Related articles: