填充下拉列表 - 避免多个数据库调用

Lam*_*mps 0 c# asp.net-mvc

我正在使用Asp.Net MVC应用程序.

在以下代码中,如何避免填充下拉列表的两个数据库调用?

[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");

}
Run Code Online (Sandbox Code Playgroud)

除了jQuery ajax方法之外的任何其他方式?谢谢

Rus*_*rke 5

它取决于数据的大小以及它可能改变的频率,但一个常见的解决方案就是使用HttpContext的Cache属性.

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;
}
Run Code Online (Sandbox Code Playgroud)