Reputation: 2221
Before anything else, please don't shoot me for being a noob who is blindly making her way to finishing an entire mvc project, albeit not starting it, alone.
So anyway, I'm completely confused as to how to implement jquery ui autocomplete in a textbox where the data comes from a database table.
I tried doing it using what I can find on the internet and here's what I came up with in my jquery function:
$(function (){
$("#autoCompleteText").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
url: "/Service/jsonAutoComplete",
success: function(result) {
response($.map(result.d, function (item){
return {
value: item.ProductName
}
}))
},
minLegth: 2
});
}
});
});
For the method in my controller here's how it looks like:
public JsonResult jsonAutoComplete(int companyId)
{
JsonResult result = new JsonResult();
Products products = new Products();
products = db.Products.FirstOrDefault(x => x.CompanyId == companyId);
int productId = products.Id;
SelectList select = this._selectFactory.CreateSelectListFromProductsByCompanyId(products.Id, companyId);
result.Data = new { select = select, productId = productId };
return result;
}
I'm pretty sure I'm doing something wrong here since nothing happens whenever I try to type the first 2 letters of one of the products on my database.
Also, what does $.map exactly mean? Most of the examples I saw on the web had this so I figured it's needed but I really don't understand it yet.
Upvotes: 0
Views: 325
Reputation: 56467
You are not sending a name of product. Try something like that:
$("#autoCompleteText").autocomplete({
source: function(request, response) {
$.ajax({
// other settings
data : {
name: request.term
}
// other settings
});
}
});
Now I don't know much about the server side technology you are using, but probably you have to do it like that:
public JsonResult jsonAutoComplete(string name) {
// TODO: search for products STARTING with name
// and return it as a JSON list
}
// EDIT
$.map
is a jQuery function which converts one array into another ( based on "converter" function ). You see this in most examples, because autocomplete
plugin requires a specific format of data, while it can be different in response from the server. So for example:
var A = [1,2,3,4,5];
var result = $.map( A, function(el) { return 10+el; } );
// result -> [11,12,13,14,15]
Upvotes: 1