使用json数据库源的文本框自动完成

时间:2012-10-04 10:40:27

标签: jquery json autocomplete

我有一个VS.NET 2010 + MVC 3.0应用程序,我在文本框上遇到了自动完成问题。 我跟随http://jqueryui.com/demos/autocomplete/的例子 一切都很棒。现在我想通过json动作填充源数组。 对于页面加载,我在IndexKPIOrder.js中调用json的GetKPIs动作。 动作GetKPIs被激活,_list0被填充,但txtKPIs文本框上没有自动完成。

任何建议都将受到赞赏。

这就是我正在做的事。

Index.cshtml:

@using NegTl.DomainModel.Model.UserCatalogues
@model IEnumerable<KPIOrder>
@{
ViewBag.Title = "KPI Ordering";
}
@section JavaScript
{
    <script type="text/javascript" src="@Url.Content("~/Scripts/helpers.js")" ></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/Views/KPIOrder/IndexKPIOrder.js")" ></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.8.2.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.ui.core.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.ui.widget.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.ui.position.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/jquery.ui.autocomplete.js")"></script>
}
<p>
    @Html.ActionLink("Create New", "Create")    
</p>
    @Html.TextBox("txtKPIs", "", new { style = "width:300px;" })
<div>
    @{
        var grid = new WebGrid(Model,
            defaultSort: "KPIOrdering",
            rowsPerPage: 20);
    }
    @grid.GetHtml(mode: WebGridPagerModes.All,
            columns: grid.Columns(
                            grid.Column(columnName: "KPIName"),
                            grid.Column(columnName: "KPIHeading"),
                            grid.Column(columnName: "KPIOrdering"),
                            grid.Column(columnName: "IsKPI"),
                            grid.Column(columnName: "IsNumeric"),
                            grid.Column(columnName: "IsNative"),
                            grid.Column(columnName: "Actions", header: "Actions", canSort: false, format: @<text>
    @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
    @Html.ActionLink("Details", "Details", new { id = item.Id }) |
    @Html.ActionLink("Delete", "Delete", new { id = item.Id })</text>)
        )
    )
</div>
@using (Html.BeginForm("NoAction", "KPIOrder", FormMethod.Post, new { id = "mockFormForAction3" })) { }

控制器:

public class KPIs
{
    public int KPIOrder { get; set; }
    public string KPIName { get; set; }
}
...
public JsonResult GetKPIs()
{
    try
    {
        List<KPIs> _list0 = new List<KPIs>();

        SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["NegociationToolEntities"].ConnectionString);
        myConnection.Open();

        SqlCommand cmd = new SqlCommand(ConfigurationManager.AppSettings["KPIListSP"], myConnection);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandTimeout = 0;

        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            _list0.Add(new KPIs { KPIOrder = Convert.ToInt32(reader["KPI_Order"]), KPIName = Convert.ToString(reader["KPI_Name"]) });
        }

        return Json(new { status = "OK", data = _list0 }, JsonRequestBehavior.AllowGet);
    }
    catch(Exception ex)
    {
        return Json(new { status = "FAIL", message = ex.Message }, JsonRequestBehavior.AllowGet);
    }
}

IndexKPIOrder.js:

$(document).ready(function () {

    var availableTagsLoad = [""];

    var url = getRootUrlFromFormAction("mockFormForAction3") + "GetKPIs";

    $(function () {
        $("#txtKPIs").autocomplete({
            source: availableTagsLoad
        });
    });

    $.ajax({
        dataType: 'json',
        delay: 400,
        autofill: true,
        selectFirst: false,
        highlight: false,
        url: url,
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            if (response.status == "OK") {
                $.each(response.data, function (index, kpi) {
                    availableTagsLoad.push(kpi.KPIName);
                });
            }
            else {
                $('#errorMessage').html(response.message);
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            $('#errorMessage').html(errorThrown);
        }
    });

})

1 个答案:

答案 0 :(得分:1)

解决方案是在创建数组后移动自动完成功能,如下所示:

$(document).ready(function () {

    var availableTagsLoad = [];
    var url = getRootUrlFromFormAction("mockFormForAction3") + "GetKPIs";

    $.ajax({
        dataType: 'json',
        delay: 400,
        autofill: true,
        selectFirst: false,
        highlight: false,
        url: url,
        contentType: "application/json; charset=utf-8",
        success: function (response) {
            if (response.status == "OK") {
                $.each(response.data, function (index, kpi) {
                    availableTagsLoad.push(kpi.KPIName);
                });

                $("#txtKPIs").autocomplete({
                    source: availableTagsLoad
                });
            }
        }
    });
})