1

^, 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)
        {
            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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the codes sample . i'll Test and see the results. ^.^
Josh M. Thanks again for your reply ^_^. May i ask if this is only possible with the creation of "ScriptMethod/WebMethod" ? PS: i'm asking this because i never "played" with "ScriptMethod/WebMethod" before, and i don't know exactly how to do this. (i spend 2h trying it =X any light to point to me ?). PS2: Sorry i'm really new at development Q.Q
I've added some more details and a link for you to read. But the code I provided is 90% of what you need. You can make test "HelloWorld" service to begin with to make sure everything is hooked up right.
Works! However, i made ​​some changes... i remove the "type: "POST"," and let the default "Default: Intelligent Guess (xml, json, script, or html)" api.jquery.com/jQuery.ajax (using script or html works too). Thanks a lot Mr. Josh M. !
0

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.

2 Comments

Thanks for the fast reply. the plugin from jquery and from JORN are the same: "This plugin is deprecated and not developed anymore. Its successor is part of jQuery UI, and this migration guide explains how to get from this plugin to the new one" i used his side as reference only, sorry for that =X i thought in use one hidden to achieve this, but even so, how can i pass both informations, should i send then and treat in the sucess clause?
What Nymos is asking is possible and pretty easy actually. Using hidden fields is not necessary (plug: see my answer).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.