I’m still working on my autocomplete textbox using data from the databse (SQL) and I think I’m not getting any result for the textbox because there’s something wrong or missing on my select statement here’s how my current code looks like. This is my json code for the view:
$(function () {
$("#autoCompleteText").autocomplete({
source: function (request, response) {
var autoSearch = { searchText: $("#autoCompleteText").val() };
$.ajax({
type: "POST",
traditional: true,
url: "/Products/jsonAutoComplete",
data: autoSearch,
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
},
delay: 0,
minLength: 2
});
});
I’m very sure that it works because whenever I run a breakpoint on my controller, the method jsonAutoComplete runs but the productName which is what I want to appear on the autcomplete, is always null. Here’s my code with the select statement:
public JsonResult jsonAutoComplete(string searchText)
{
JsonResult data= new JsonResult();
IList<Products> products = null; products = (from c in db.Products where c.CompanyId.Equals(companyId) && (c.ProductName.Contains("'%" + searchText + "%'")) select c).ToList();
Products prod = new Products();
int productId = prod.Id;
string productName = prod.ProductName;
data.Data = new { productId = productId, productName = productName };
return data;
}`
You can’t use SQL operators or SQL syntax in Linq, because that’s the point: Linq is meant to abstract away SQL, because
%is T-SQL specific wildcard syntax.Simply having this predicate will work:
However Linq really doesn’t work very well for freetext searches. For a better searching system I’d use SQL Server Full-Text Indexes, then generate Dynamic SQL that searches for each term in the search query, rather than a naïve string search (as it gives the user more control and search results, and makes it behave more like Google).