开发者

Populate dropdownlist - avoid multiple database calls

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 drop开发者_StackOverflow社区down

Return View("Upload");

}

Any other way than jQuery ajax method? Thanks


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜