Create a new ASP.net mvc3 project autocomplete.
Import the JS library to implement AutoComplete in the Shared/_layout.cshtml master page
<! DOCTYPE html>
Model, create a new singer class
public class Singer
{public
int Singerid {get; set;}
public string Singername {get; set;}
}
Project----Add asp.net folder----App_Data
To add a connection string in Web.config
<connectionStrings>
<add name= "autodbentities" connectionstring= "Data source=.\sqlexpress;initial Catalog=autocomplete; Persist Security info=true; User Id=sa; Password=xxx "providername=" System.Data.SqlClient "/>
</connectionStrings>
Model to create a new inherited DbContext class AutoDbEntities.cs
public class Autodbentities:dbcontext
{public
dbset<singer> singers {get; set;}
}
Model to create a new inheritance:D ropcreatedatabaseifmodelchanges<autodbentities> to implement seeding data class InitData.cs
public class initdata:dropcreatedatabaseifmodelchanges<autodbentities>
{
protected override void Seed (autodbentities context)
{Context
. Singers.add (new Singer {singername = "Jay Chou"});
Context. Singers.add (new Singer {singername = "weekly Pen Chang"});
Context. Singers.add (new Singer {singername = "kin"});
Context. Singers.add (new Singer {singername = "a"});
Context. Singers.add (new Singer {singername = "123"});
Context. Singers.add (new Singer {singername = "1234"});
Base. Seed (context);
}
Modify the Global.asax file to set the seeding database
protected void Application_Start ()
{
System.Data.Entity.Database.SetInitializer (new AutoComplete.Models.InitData ()); If the database does not exist, initialize the data
arearegistration.registerallareas ();
Registerglobalfilters (globalfilters.filters);
RegisterRoutes (routetable.routes);
}
Create a new Homecontrolle in controllers
Add the index () method to display the view,
Add the QuickSearch () method to implement the asynchronous query, return the JSON data to the view, and display on the search box
public class Homecontroller:controller
{
autodbentities db = new autodbentities ();
Public ActionResult Index ()
{return
View ();
}
Public ActionResult QuickSearch (string term)
{
var singers = getsingers (term). Select (a => new {value = A.singername});
Return Json (singers, jsonrequestbehavior.allowget);
Private list<singer> Getsingers (string searchstring)
{return
db. Singers.where (a => a.singername.contains (searchstring)). ToList ();
}
Add a view to the index () method for HomeController
Add a search box to the index.cshtml view and add the Data-autocomplete-source property to handle the property in the ready event of the DOM
@{
viewbag.title = "Index";
}
Run the program, the effect is as follows