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

本文关键字:数据库 调用 下拉列表 填充 | 更新日期: 2023-09-27 18:02:18

我正在使用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");
}

还有其他方法比jQuery ajax方法吗?由于

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

这取决于数据的大小和它可能改变的频率,但一个常见的解决方案就是使用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;
}

我倾向于缓存像这样很少更改的数据。

Checkout EntLibs Caching Application block .

您可以在第一次使用时将所有数据加载到缓存中,并根据您希望数据库中的更改生效的速度设置过期时间。

基本上,在你的控制器和数据库之间添加一个层,运行类似这样的代码:
        MyData myData = null;
        myData = (MyData )cacheManager.GetData("myData");
        if (myData == null)
        {
            myData = dataProvider.GetData();
            cacheManager.Add("myData", myData, CacheItemPriority.Normal, null, timeToExpire);
        }
        return myData;

myData是下拉菜单中需要的数据。