Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC, autocomplete textbox, caching?

Using ASP.NET MVC, I've implemented an autocomplete textbox using the approach very similar to the implementation by Ben Scheirman as shown here: http://flux88.com/blog/jquery-auto-complete-text-box-with-asp-net-mvc/

What I haven't been able to figure out is if it's a good idea to cache the data for the autocomplete textbox, so there won't be a roundtrip to the database on every keystroke?

If caching is prefered, can you guide me in the direction to how to implement caching for this purpose?

like image 230
Tommy Jakobsen Avatar asked Jan 23 '23 09:01

Tommy Jakobsen


1 Answers

You have a couple things to ask yourself:

  1. Is the data I'm pulling back dynamic?
  2. If not, how often do I expect this call to occur?

If the answers are, 1- not really and 2 - call to happen frequently, you should cache it.

I don't know how your data access is setup, but I simply throw my data into cache objects like so:

public IQueryable<Category> FindAllCategories()
{
    if (HttpContext.Current.Cache["AllCategories"] != null)
        return (IQueryable<Category>)HttpContext.Current.Cache["AllCategories"];
    else
    {
        IQueryable<Category> allCats =  from c in db.Categories
                                          orderby c.Name
                                          select c;

        // set cache
        HttpContext.Current.Cache.Add("AllCategories", allCats, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 0, 30, 0, 0), System.Web.Caching.CacheItemPriority.Default, null);
        return allCats;
    }
}

This is an example of one of my repository queries, based off of LINQ to SQL. It first checks the cache, if the entry exists in cache, it returns it. If not, it goes to the database, then caches it with a sliding expiration.

like image 60
Chaddeus Avatar answered Jan 27 '23 06:01

Chaddeus