使用 C# LINQ 填充/加载列表一次以提高性能



我正在开发一个 ASP.NET MVC 4.5应用程序。我需要在下拉列表中填充一个列表。无论如何,我不能正常工作,当我单击该字段时,有一个服务器请求。

我想在客户端初始加载后存储值以加快应用程序速度。

我正在使用视图模型在我的剃刀视图中填充列表。

您知道如何实现此的初始负载吗?

这是我的数据源控制器:

public JsonResult GetBusinessLineList(string id = null, string query = null)
{
    return
        Json(Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList(), 
            JsonRequestBehavior.AllowGet);
}

剃刀视图:

<div class="form-group">
    @Html.LabelFor(model => model.BusinessLineIdList, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.Select2AjaxFor(model => model.BusinessLineIdList, @Url.Action("GetBusinessLineList", "DataSource"),
               new { @class = "form-control"))
    </div>
</div>

非常感谢和亲切的问候!

您可以尝试使用输出缓存:

[OutputCache(Location = OutputCacheLocation.Client, VaryByParam = "id;query", Duration = 3600)]
public JsonResult GetBusinessLineList(string id = null, string query = null)
{
    return Json(Db.BusinessLine.AsQueryable()
        .Where(x => x.Label.Contains(query))
        .Take(10)
        .Select(x => new { id = x.BusinessLineId, text = x.Label })
        .ToList(), 
        JsonRequestBehavior.AllowGet);
}

OutputCacheLocation.Client - 指定仅在客户端上缓存结果。还有其他选项可用。

VaryByParam = "id;query" - 需要根据方法参数来区分缓存结果。

Duration - 缓存持续时间(以秒为单位(。

你需要一些缓存策略,这里是简单的缓存助手类

using System.Runtime.Caching;  
public class cacheservice: ICacheservice
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}
interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}

用法:

cacheservice.GetOrSet("CACHEKEY", (delegate method if cache is empty));
缓存

提供程序将检查缓存中是否有名为"CACHEKEY"的任何内容,如果没有,它将调用委托方法来获取数据并将其存储在缓存中。

例:

var Data=cacheService.GetOrSet("CACHEKEY", ()=>SomeRepository.GetData());

在您的情况下,它会像

var Data=cacheService.GetOrSet("CACHEKEY", Db.BusinessLine.AsQueryable()
            .Where(x => x.Label.Contains(query))
            .Take(10)
            .Select(x => new { id = x.BusinessLineId, text = x.Label })
            .ToList());

您也可以根据需要进行定制

使用这些缓存策略,它将第一次加载数据并存储在缓存中,第二次它将从缓存中获取值,而不是往返数据库。

最新更新