How to filter occupation as you type in MVC3
I have a list of 2500 occupa开发者_开发知识库tions held in our db. On our site we ask for you to enter your occupation and I would like it to filter the results as they type; like Play.com's search. Is there a way to do this in MVC3?
Appreciate any help.
You can do this using a autocomplete javascript.
For example: http://www.pnpguidance.net/post/jQueryAutoCompleteASPNETMVCFramework.aspx
You can grab your data using jQuery Ajax.
I would create an action method that would return JSON:
[HttpGet()]
public JsonResult Occupations(String searchCriteria)
{
String[] occupations = new String[] { "Lawyer", "Carpenter" };
return Json(occupations.Where(s => s.Contains(searchCriteria))
.ToList(), JsonRequestBehavior.AllowGet);
}
If you run a GET request on this link: /Occupations?searchCriteria=Carpenter you'll receive ["Carpenter"] in a response.
I would make a jQuery ajax call to this action method. On success, I would take a reponse and generate an output such as list of li elements to select from.
Example of an ajax json get request is below:
$.ajax({
type: 'json',
url: '/Occupations',
type: 'GET',
cache: false,
data: { searchCriteria: searchCriteria},
error: function () {
},
success: function (result) {
alert(result);
}
});
This is from a notepad, so there might be some minor syntax errors.
精彩评论