如何使用ASP.NET从MSSQL的JQuery自动完成小部件获取数据

时间:2018-10-23 12:22:02

标签: javascript jquery asp.net autocomplete

我下载了jquery-ui以使用自动完成小部件,并且希望从MSSQL数据库中获取项目。但是我不知道如何在带有SQL的ASP.NET中使用它。代码基本上如下所示。

 <div>
        <input id="autocomplete" title="type &quot;a&quot;">
    </div>
StringBuilder strScript = new StringBuilder();
        strScript.Append("var availableTags = ['java','javascript'];");
        strScript.Append("$('#autocomplete').autocomplete({");
        strScript.Append("source: availableTags});");
        Page.ClientScript.RegisterStartupScript(this.GetType(), "Script",
        strScript.ToString(), true);

编辑:只需找出操作方法即可。只需使用以下代码将jquery复制到服务器端:

{{1}}

1 个答案:

答案 0 :(得分:0)

首先,您需要编写代码的后端以从SQL获取数据。然后,您将使用JQuery调用此函数,并且需要将此值设置为自动完成源。

因此您的自动填充代码应如下所示。

$("#YourAutoCompleteInputId").autocomplete({
    autoFocus: true, 
    delay: 0,
    scrollIntoView: false,
    source: function (request, response) {
        $.get("/YourControllerName/YourControllerMethod/", { searchTerm: request.term }, function (data) {
            response($.map(data, function (item) {
                return {
                    label: item.Name 
                    val: item.Id
                }
            }));
        }).fail(function () {
            alert("error");
        });
    },
    select: function (event, ui) {
        // whatever you return from your back-end code. you can reach here
        // you can reach it by using ui.item.label => it's your label and ui.item.val => is your value. 
        // do something when user select one the result from autocomplete list.
    },
    open: function () {
        // do something when user open autocomplete list
    },
    close: function () {
        // do something when user close autocomplete list
    }
});

您的方法应该是这样的。

public async Task<JsonResult> GetApplicantNamesForAutoComplete(string searchTerm)
{
    var list = yourData.Where(x => x.yourTableColumnName.Contains(searchTerm))
        .Select(x => new { x.Id, Name = (x.FirstName + " " + x.LastName)});
    return Json(await list.ToListAsync(), JsonRequestBehavior.AllowGet);
}