快速尝试时,AJAX搜索不会返回准确的结果

时间:2017-03-20 15:42:47

标签: c# jquery ajax asp.net-mvc

我正在使用NonFactors.Mvc.Grid进行搜索。除非我忽视了一些明显的事情,否则我实施它as shown here

在父视图中,我有这一行生成网格:

@Html.AjaxGrid(Url.Action("UserSearch", new { }))

我有搜索文本框:

@Html.TextBoxFor(x => x.WildCardSearch, new { @class = "form-control per90 mt5 mr5 pull-left", placeholder = "Search", autofocus = "autofocus" })<i class="fa fa-125 fa-search"></i>

最终会产生这个:

<input 
    autofocus="autofocus" 
    class="form-control per90 mt5 mr5 pull-left" 
    id="WildCardSearch" 
    name="WildCardSearch" 
    placeholder="Search" 
    type="text" 
    value="">

这是处理它的客户端方法:

$(document).on('keyup', '#WildCardSearch', function () {
    $('.mvc-grid').mvcgrid({
        query: 'search=' + this.value,
        reload: true
    });
});

这是执行搜索的服务器端方法:

public PartialViewResult UserSearch(string search)
{
    var results = // Initial query that returns an IQueryable of all the raw results. 

    if (!string.IsNullOrEmpty(search))
    {
        search = search.ToLower();
        results = from r in results
                  let bothNames = r.LastName + ", " + r.FirstName
                  where
                   r.FirstName.ToLower().Contains(search) ||
                   r.LastName.ToLower().Contains(search) ||
                   bothNames.ToLower().Contains(search) ||
                   r.Phone.Contains(search) ||
                   r.Email.Contains(search)
                  select r;
        }
        return PartialView(results);
}

现在,这就是......

如果我在搜索文本框中输入非常慢,并等待每个按键处理,那么结果始终是100%准确的。但是,如果我输入速度很快,那么结果就会全部结束。有时这是准确的,但大部分时间都不准确。

1 个答案:

答案 0 :(得分:0)

通过搜索和啄多个线程,我想出了这个解决方案:

<script>

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 1000;  //time 1 seconds

//on keyup, start the countdown
$('#WildCardSearch').on("keyup", function () {
    if (typingTimer) clearTimeout(typingTimer);                 // Clear if already set     
    typingTimer = setTimeout(DoTheSearch, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#WildCardSearch').on("keydown", function () {
    clearTimeout(typingTimer);
});

function DoTheSearch() {
   ... ajax call to the server
}

</script>