0

I am using a Asp.Net MVC application.

In the following code how can I avoid the two database calls for populating a dropdown?

[HttpGet]
public ActionList Upload(){

// do something
//For populating drop downlist take data from db

Return View("Upload");

}

[HttpPost]
public ActionList Upload(){

//do something
//again take data from db for populating dropdown

Return View("Upload");

}

Any other way than jQuery ajax method? Thanks

2 Answers 2

5

It depends on the size of the data and how often it's likely to change, but a common solution is just to use the HttpContext's Cache property.

public List<items> GetDropdownlistItems()
{
    string cacheKey = "dropdownlistItems";

    if (HttpContext.Current.Cache[cacheKey] != null)
    {
        return (List<items>)HttpContext.Current.Cache[cacheKey];
    }

    var items = GetItemsFromDatabase();

    HttpContext.Current.Cache.Insert(cacheKey, items, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);

    return items;
}
Sign up to request clarification or add additional context in comments.

4 Comments

hi... My dropdown contains around 50 items. Is it ok to store it cache? Will it cause any performance issue?
That shouldn't be too bad; If the Garbage Collector decides it needs more memory then it will likely remove the items from the Cache first but that behaviour is managed by system so shouldn't be anything you need to worry about.
Ok thanks. If the user has disabled cache in browser means, caching wont work?
The cache is handled server side.
1

I tend to cache data that is rarely changed such as this.

Checkout EntLibs Caching Application Blocks.

You can load all data into the cache on first use, and set an expiry time depending on how quickly you want changes in the db to be made effective.

Basically, add a layer between your Controller and the Database, that runs code something like this:

        MyData myData = null;
        myData = (MyData )cacheManager.GetData("myData");

        if (myData == null)
        {
            myData = dataProvider.GetData();
            cacheManager.Add("myData", myData, CacheItemPriority.Normal, null, timeToExpire);
        }

        return myData;

Where myData is the data you need for a dropdown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.