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

标签 c# asp.net asp.net-mvc linq razor

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

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

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

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

这是我的数据源 Controller :

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

Razor View :

<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 - 以秒为单位的缓存持续时间。

关于c# - 使用 c# linq 一次填充/加载列表以提高性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117301/

相关文章:

asp.net - Windows 和匿名身份验证并排

c# - 如何更改 Autofac 中具有较长生命周期的对象中的值?

c# - 根据对象的某些属性创建唯一的哈希码

javascript - 复选框在 gridview asp.net 中使用 Shift 键进行多项选择

c# - 如果您在加载页面后闲置时间过长,则 Http 文件上传失败 (asp.net mvc)

asp.net-mvc - 你能创建一个 int 或 enum 类型的强类型 ASP.NET MVC ViewUserControl 吗?

c# - 如何在 ASP.NET MVC 5 中为特定 Controller 指定路由选项

javascript - 来自 javascript 对象的 @Html.Partial 期间未终止的字符串常量

c# - 无法将指定的节点作为该节点的有效子节点插入,因为指定的节点类型错误

c# - Raspberry Pi+MonoDevelop如何从串口读取数据?