简体   繁体   English

在我的MVC3应用程序中使用jQuery自动完成功能

[英]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. 因此,当他们输入城市名称时, jQuery UI组件的自动完成选项将异步加载。

The example on the page shows how to use a .php file, but how does this fit into a pure HTTP solution? 页面上的示例显示了如何使用.php文件,但这如何适合纯HTTP解决方案?

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. 自动完成插件会将GET请求发送到使用?term=blah querystring参数指定的路径。

You need to add an Action to your controller to handle this request, and return an array of matching values as json. 您需要向控制器添加一个Action来处理此请求,然后将匹配值的数组作为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. 然后在您的JavaScript中,像这样连接autcomplete函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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