1

I have a VS.NET 2010 + MVC 3.0 application and I've got a autocompletion problem on a textbox. I was following example from http://jqueryui.com/demos/autocomplete/ All works great. Now I want to populate source array by json action. For this on page load I'm calling GetKPIs action by json in IndexKPIOrder.js. Action GetKPIs is well fired and _list0 is filled, but no autocompletion on txtKPIs textbox.

Any suggestions will be appreciated.

This is what I'm doing.

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" })) { }

Controller:

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

})
4

1 回答 1

1

Solution was to move autocomplete function just after array creation, like this:

$(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
                });
            }
        }
    });
})
于 2012-10-09T14:47:45.583 回答