下面是我在我的 ASP MVC 3 视图中为他们的typeahead.js插件使用的 jQuery 代码。
$('#typeahead').typeahead({
source: function (term, process) {
var url = '@Url.Content("~/Agent/GetAgents")';
var agents = [];
map = {};
return ($.getJSON(url, { term: term }, function (data) {
$.each(data, function (i, item) {
map[item.Name] = item;
agents.push(item.Name);
});
process(agents);
}));
},
highlighter: function (item) {
var p = map[item];
var display = ''
+ "<div class='typeahead_wrapper'>"
+ "<div class='typeahead_labels'>"
+ "<div class='typeahead_primary'>" + p.Name + </div>
+ "<i>LastFour:</i>" + p.LastFour + "</div>"
+ "<div class='typeahead_third'>" + "<i>Agent IDs:</i> " + p.AgentIds + "</div>"
+ "</div>"
+ "</div>";
return display;
},
updater: function (item) {
window.location.href = ("/Agent/Details/" + map[item].sNumber);
}
});
代码在控制器中调用此GetAgents
方法。整个过程按预期完成,但完成此过程几乎需要一分钟。
[HttpGet]
public JsonResult GetAgents(string term)
{
term = term.ToUpper();
var agents = (from a in db.Agent
where a.FirstName.Contains(term) ||
a.LastName.Contains(term)
select a).AsEnumerable()
.Select(x => new
{
Name = x.FirstName + " " + x.LastName,
sNumber = x.sNumber,
LastFour = x.DisplayTaxId,
AgentIds = String.Join(", ", from b in db.sNumberToAgentId
where b.sNumber == x.sNumber
select b.AgentId)
});
var corps = (from a in db.Agent
where a.CorporateName.Contains(term)
select a).AsEnumerable()
.Select(x => new
{
Name = x.FirstName + " " + x.LastName,
sNumber = x.sNumber,
LastFour = x.DisplayTaxId,
AgentIds = String.Join(", ", from b in db.sNumberToAgentId
where b.sNumber == x.sNumber
select b.AgentId)
});
return new JsonResult()
{
Data = (agents.Union(corps).ToArray()),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
单步执行代码,问题似乎出在这部分。有谁知道加快这样的呼叫的方法或为什么会发生这种情况?
return new JsonResult()
{
Data = (agents.Union(corps).ToArray()),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
编辑
我将查询更改为下面的这个结构,但是现在我得到了OutOfMemory Exception
var agents = (from a in db.Agent
from b in db.sNumberToAgentId
join b in db.sNumberToAgentId on a.sNumber equals b.sNumber into apm
where a.FirstName.Contains(term) || a.LastName.Contains(term)
select new
{
Name = a.FirstName + " " + a.LastName,
sNumber = a.sNumber,
LastFour = a.DisplayTaxId,
AgentIds = b.AgentId
}).ToList();