Asp.Net和AutoComplete(jQuery)之间的交互

时间:2011-03-17 14:31:39

标签: jquery .net asp.net autocomplete jquery-ui-autocomplete

^, 首先:抱歉我的英语= X

我正在创建一个自动完成组件,我遇到了一些问题。

我通过ajax将一些参数传递给我的aspx页面。

jQuery代码:


/* AutoComplete */

$(function () {
    $('.ACCascata').bind('keyup', function () {

        // Criação do apontamento
        var tipoObj = $(this).attr("tipo").toString();

        $(this).autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "AutoComplete.aspx",
                    dataType: "json",
                    data: {
                        tipo: tipoObj, //Apontamento
                        q: request.term //Item digitado no input
                    },
                    success: function (event, ui) {
                        response(event);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        //alert(xhr.status);
                        //alert(thrownError);
                    }
                });
            }
        });
    });
});

.Net代码


public class AutocompleteItem
        {
            private String id;

            public String Id
            {
                get { return id; }
                set { id = value; }
            }

            private String value;

            public String Value
            {
                get { return this.value; }
                set { this.value = value; }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            switch (Request.QueryString["tipo"])
            {
                case "pais":
                    this.BuscaPaises(Request.QueryString["q"]);
                    break;
                case "estado":
                    this.BuscaEstados(Request.QueryString["q"]);
                    break;
                case "cidade":
                    this.BuscaCidades(Request.QueryString["q"]);
                    break;
            }
        }

        private void BuscaPaises(string query)
        {
            try
            {
                AcessoDados BuscaLocal = new AcessoDados();
                BuscaLocal.OpenConnection();

                String SqlSelect = "SELECT ID, Nome FROM Paises Where Nome like '%" + query + "%'";

                BuscaLocal.Select(SqlSelect);

                //ArrayList resultado = new ArrayList();
                ArrayList result = new ArrayList();

                while (BuscaLocal.Records.Read())
                {
                    AutocompleteItem autoCompletar = new AutocompleteItem();
                    autoCompletar.Id = BuscaLocal.Records["ID"].ToString();
                    autoCompletar.Value = BuscaLocal.Records["Nome"].ToString();

                    //resultado.Add(autoCompletar);
                    result.Add(BuscaLocal.Records["Nome"].ToString());
                }

                BuscaLocal.CloseConnection();

                JavaScriptSerializer js = new JavaScriptSerializer();

                //string jsonResult = js.Serialize(resultado);
                string jsonResult = js.Serialize(result);

                Response.Write(String.Format("{0}", jsonResult));
            }
            catch (Exception falhaSelect)
            {
                throw falhaSelect;
            }
        }

抱歉,葡萄牙语= X

上面的代码“有效”,但只发送名称(当然,这是我唯一通过的东西)。评论代码(3行)让我感到痛苦......

我正在尝试发回ID和名称(Nome in portuguese),但我不知道如何实现这一目标。

使用:

BAssistance AutoComplete from JÖRN ZAEFFERER

Asp.Net FrameWork 3.5。

2 个答案:

答案 0 :(得分:1)

我刚做了类似的练习。我用ScriptMethod / WebMethod来处理这个问题。这是一些代码:

为您的项目添加一个新的“Web服务”,我称之为“Service.asmx”并使您的服务看起来像这样:

namespace Some.Thing
{
    [WebService(Namespace = "http://some.thing")]
    [ScriptService]
    public class Service : System.Web.Services.WebService
    {
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public Suggestion[] GetSuggestions(string text, int count)
        {
            using (MyDataContext context = new MyDataContext())
            {
                return (from a in context.Airports
                        ...
                        select new Suggestion()
                        {
                            ID = a.ID,
                            Text = a.ToString()
                        }).ToArray();
            }
        }

        public struct Suggestion
        {
            public string ID { get; set; }
            public string Text { get; set; }
        }
    }
}

编辑您的Web.Config并添加这些行以启用WebMethod \ ScriptMethod行为:

<system.web>
    <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
<system.web>

尝试在浏览器中访问它来测试您的服务:

http://localhost/Service.asmx/Suggestions?text=abc&count=10

然后你可以用JavaScript调用你的新服务方法:

$("#" + fromTextBoxID).autocomplete(
{
    source: function (request, response)
    {
    $.ajax(
    {
        url: "/Service.asmx/GetSuggestions",
        type: "POST",
        async: false,
        contentType: "application/json",
        data: "{ text: \"" + request.term + "\", count: 10 }",
        success: function (data)
        {
        var items = new Array();

        for (var i = 0; i < data.d; i++)
            items[items.length] = { value: data.d[i].ID, label: data.d[i].Text };

        response(items);
        },
        error: goTravel.HandleAjaxError
    });
    },
    minLength: 1
});

有关其他信息,请结帐this article on MSDN

答案 1 :(得分:0)

我的经验是使用Jquery.UI自动完成,所以它可能有点不同,但我们采用的方法是为每个自动完成字段设置一个匹配的隐藏字段,并为自动完成设置更改事件的处理程序隐藏字段中的id。然后你可以正常处理提交。