开发者

Interaction between Asp.Net and AutoComplete (jQuery)

^, first of all: Sorry for my english =X

I'm creating an autocomplete componente and i'm having some issues.

I'm passing via ajax some parameters to my aspx page.

jQuery Code:


/* 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 code


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)
   开发者_C百科     {
            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;
            }
        }

Sorry, portuguese =X

the code above "works" but only sends the name (of course, it's the only thing that i'm passing). The commented code (3 lines) is what is giving me pain...

i'm trying send back ID and Name (Nome in portuguese), but i don't know how achieve this.

using :

BAssistance AutoComplete from JÖRN ZAEFFERER .

Asp.Net FrameWork 3.5.


I just did a similar exercise. I used a ScriptMethod/WebMethod to handle this. Here is some code:

Add a new "Web Service" to your project, I called mine "Service.asmx" and make your service look something like this:

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

Edit your Web.Config and add these lines to enable the WebMethod\ScriptMethod behavior:

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

Test your service by trying to visit it in a browser:

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

Then you can call your new service method from JavaScript like this:

$("#" + 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
});

For additional information, checkout this article on MSDN.


My experience is with the Jquery.UI Autocomplete so it may be a little different but the approach we took on this is to have a matching hidden field for each Autocomplete field and a handler for the change event of the Autocomplete that would set the id in the hidden field. Then you can handle submits normally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜