【问题标题】:Interaction between Asp.Net and AutoComplete (jQuery)Asp.Net 和 AutoComplete (jQuery) 之间的交互
【发布时间】:2011-07-17 11:06:14
【问题描述】:

^, 首先:对不起我的英语=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),但我不知道如何实现。

使用:

BAssistance AutoComplete from JÖRN ZAEFFERER .

Asp.Net 框架 3.5.

【问题讨论】:

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


    【解决方案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

    【讨论】:

    • 感谢您提供代码示例。我会测试并查看结果。 ^.^
    • Josh M. 再次感谢您的回复 ^_^。请问这是否只能通过创建“ScriptMethod/WebMethod”来实现? PS:我问这个是因为我以前从未“玩过”“ScriptMethod/WebMethod”,而且我不知道该怎么做。 (我花了 2 小时尝试它=X 任何光指向我?)。 PS2:对不起,我是开发Q.Q的新手
    • 我添加了更多详细信息和链接供您阅读。但是我提供的代码是你需要的 90%。您可以首先测试“HelloWorld”服务,以确保一切都正确连接。
    • 有效! 但是,我做了一些更改......我删除了“类型:“POST”,并让默认的“默认:智能猜测(xml , json, script, or html)" api.jquery.com/jQuery.ajax (使用 script 或 html 也可以)。非常感谢 Josh M. 先生!
    【解决方案2】:

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

    【讨论】:

    • 感谢您的快速回复。 jquery 和 JORN 的插件是相同的:“这个插件已弃用,不再开发。它的继任者是 jQuery UI 的一部分,这个迁移指南解释了如何从这个插件到新插件”我用他的一面作为仅供参考,抱歉 =X 我认为使用一个隐藏来实现这一点,但即便如此,我怎样才能传递这两个信息,我应该发送然后在 sucess 子句中处理?
    • Nymos 的要求是可能的,而且实际上非常简单。不需要使用隐藏字段(插件:请参阅我的答案)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 1970-01-01
    • 2011-09-07
    • 2012-09-06
    • 2016-11-11
    • 2016-05-15
    相关资源
    最近更新 更多