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

Tim*_*ton 5 c# linq asp.net asp.net-mvc razor

我正在研究ASP.NET MVC 4.5应用程序.我需要在下拉列表中填充列表.我工作正常,无论如何,当我点击该字段时总是有服务器请求.

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

我正在使用ViewModel来填充Razor View中的列表.

你知道如何实现这个的初始加载吗?

这是我的DataSource控制器:

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

剃刀视图:

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

非常感谢和亲切的问候!

Ale*_*rt. 7

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

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

OutputCacheLocation.Client - 指定您只想在客户端上缓存结果.还有其他选择.

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

Duration - 缓存持续时间(秒).