I have an autocomplete in my MVC 4 application that connects to a database of all the cities in the world (so you can imagine that its pretty large). It works fine on the PC, but when I go to the site on my smartphone, it takes a good 3 seconds to load and performance becomes really sluggish. Would using Ajax or JSON make it faster? Here's the code (I'm using the code from the pluralsight tutorials):
Part of View + Javascript
<!--Searching through all the hotel locations -->
<p>Hotel Location (City): @Html.TextBoxFor(x => x.booking_instance.Location,
new { data_autocomplete = @Url.Action("QuickSearch", "Booking") })</p>
<script type="text/javascript">
$(document).ready(function () {
$(":input[data-autocomplete]").each(function () {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
});
</script>
Controller
// this is my database of cities.
TE_TSQL1_HBOSDataContext _db = new TE_TSQL1_HBOSDataContext();
public ActionResult QuickSearch(string term)
{
var cities = _db.Cities
.Where (r => r.CityName.Contains(term))
.Select(r => new { label = (r.CityName + ", " + r.CountryName) });
return Json(cities, JsonRequestBehavior.AllowGet);
}
Yes! using Jquery and Ajax will definitely make it faster on your mobile phone as you wont have to load the full dataset into the phones memory and then search it. You can let the C# server do the select and then return just the data you want. The best part is, your server is already returning JSON results, and you can have the mobile device make its first query after 2 characters have been entered, greatly limiting the size of the dataset returned.
$( ":input[data-autocomplete]" ).autocomplete({
source: "controllerPath/QuickSearch",
minLength: 2
});