简体   繁体   中英

Using jQuery autocomplete in my MVC3 application

I'm making a registration form for my users and I'd like them to write in their city.

So as they type in a city name, the auto-complete options of the jQuery UI component would load asynchronously.

The example on the page shows how to use a .php file, but how does this fit into a pure HTTP solution?

How do I fetch these options?

I have a simple table accessed using Entity Framework and the repository pattern:

table City
------------------
CityId int primary key,
Name nvarchar(256)

The autocomplete plugin will send a GET request to the path you specify with a ?term=blah querystring parameter.

You need to add an Action to your controller to handle this request, and return an array of matching values as json.

public ActionResult AutoCompleteCity(string term) {
  var db = new myEFDataContext();
  return Json(db.Cities.Where(city => city.Name.StartsWith(term)).Select(city => city.Name), JsonRequestBehavior.AllowGet);
}

Then in your javascript you hook up the autcomplete function like so.

$('#cityTextBoxId').autocomplete({ source: '/Controller/AutoCompleteCity' });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM