如何通过调用asp.net web方法在bootstrap twitter typeahead上进行远程调用

时间:2016-01-16 07:01:44

标签: c# jquery asp.net typeahead.js bloodhound

我正在尝试使用typeahead.js bloohound's函数加载remote,我可以调用我的Web方法。我见过使用querystring的类似线程:

  1. Integrating Typeahead.js with ASP.Net Webmethod
  2. Typeahead.js and Bloodhound.js integration with C# WebForms WebMethod
  3. http://yassershaikh.com/using-twitter-typeahead-js-with-asp-net-mvc-web-api/
  4. 还有更多......

    但是,我找不到使用ajaxwebmethod

    调用typeahead.js.的示例

    所以这就是我目前的工作原理:

    的WebMethod

        [WebMethod]
        public static string GetEmployeeTypeahead()
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            jss.MaxJsonLength = 100000000;
            string json;
    
            using (var rep = new RBZPOS_CSHARPEntities())
            {
                var result = rep.Employees
                                .Where(x => x.EMPLOYEESTATE == 1)
                                .Select(x => new { 
                                    x.EMPLOYEEID,
                                    x.FULLNAME,
                                    x.MANNO,
                                    x.NRC
                                }).ToList();
    
                json = jss.Serialize(result);
            }
    
            return json;
        }
    

    客户

            function LoadEmployeeJSON() {
            $.ajax({
                type: "POST",
                url: "/WebMethods/Test.aspx/GetEmployeeTypeahead",
                data: "{}",
                contentType: "application/json",
                dataType: "json",
                success: function (msg) {
                    empList = $.parseJSON(msg.d);                  //otherwise does not work
    
                    LoadEmployeeTypeahead();
                },
                error: function (msg) {
                    alert("error:" + JSON.stringify(msg));
                }
            });
    
        }
        function LoadEmployeeTypeahead() {
            var empData = empList;
    
            var fullname = new Bloodhound({
                datumTokenizer: function (d) {
                    return Bloodhound.tokenizers.whitespace(d.FULLNAME)
                },
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                local: empData,
                limit: 10
            });
    
            fullname.initialize();
            // Make the code less verbose by creating variables for the following
            var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');
    
            // Initialise typeahead for the employee name
            fullnameTypeahead.typeahead({
                highlight: true
            }, {
                name: 'FULLNAME',
                displayKey: 'FULLNAME',
                source: fullname.ttAdapter(),
                templates: {
                    empty: [
                                        '<div class="empty-message">',
                                        'No match',
                                        '</div>'
                    ].join('\n'),
                    suggestion: function (data) {
                        return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
                    }
                }
            });
    
            var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
                /* See comment in previous method */
                $('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
                $('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
                $('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
                $('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);
    
            };
    
            // Associate the typeahead:selected event with the bespoke handler
            fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
        }
         function clearAndReInitilize() {
    
            $('.typeahead').typeahead('destroy');
            $('.typeahead').val('');
        }
    

    因此,您可以看到我正在拨打local来代替remote

    如何使用remote功能调用webthod并填写typeahead而不使用任何querystrings

1 个答案:

答案 0 :(得分:0)

好吧终于通过ashx通用处理程序让它工作了。因此,我使用以下ashx处理程序而不是使用Web方法:

 public class Employess : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        jss.MaxJsonLength = Int32.MaxValue;
        string json;
        string prefixText = context.Request.QueryString["query"];

        using (var rep = new RBZPOS_CSHARPEntities())
        {
            var result = rep.Employees
                             .Where(x => x.EMPLOYEESTATE == 1 && x.FULLNAME.Contains(prefixText.ToUpper()))
                             .Select(x => new
                             {
                                 x.EMPLOYEEID,
                                 x.FULLNAME,
                                 x.MANNO,
                                 x.NRC
                             }).ToArray();

            json = jss.Serialize(result);
        }

        context.Response.ContentType = "text/javascript";
        context.Response.Write(json);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

以下是对ashx处理程序的jquery和ajax调用

 $(document).ready(function () {
        $(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
        LoadEmployeeTypeahead();
      //  LoadEmployeeJSON();
    });
 function LoadEmployeeTypeahead() {
        //var empData = empList;

        var fullname = new Bloodhound({
            remote: {
                url: '/Employess.ashx?query=%QUERY',
                wildcard: '%QUERY'
            },
            datumTokenizer: function (d) {
                //var employees = $.parseJSON(msg.d);
                return Bloodhound.tokenizers.whitespace(d.FULLNAME)
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            limit: 10
        });

        fullname.initialize();
        // Make the code less verbose by creating variables for the following
        var fullnameTypeahead = $('#<%=txtFullName.ClientID %>.typeahead');

        // Initialise typeahead for the employee name
        fullnameTypeahead.typeahead({
            highlight: true
        }, {
            name: 'FULLNAME',
            displayKey: 'FULLNAME',
            source: fullname.ttAdapter(),
            templates: {
                empty: [
                                    '<div class="empty-message">',
                                    'No match',
                                    '</div>'
                ].join('\n'),
                suggestion: function (data) {
                    return '<h6 class="">' + data.FULLNAME + "<span class='pull-right text-muted small'><em>" + data.MANNO + "</em></span><span class='pull-right text-muted small'><em>" + data.NRC + "</em></span>" + '</h6>';
                }
            }
        });

        var fullnameSelectedHandler = function (eventObject, suggestionObject, suggestionDataset) {
            /* See comment in previous method */
            $('#<%=txtFullName.ClientID %>').val(suggestionObject.FULLNAME);
            $('#<%=txtEmployeeID.ClientID %>').val(suggestionObject.EMPLOYEEID);
            $('#<%=txtManNo.ClientID %>').val(suggestionObject.MANNO);
            $('#<%=txtNRC.ClientID %>').val(suggestionObject.NRC);

        };

        // Associate the typeahead:selected event with the bespoke handler
        fullnameTypeahead.on('typeahead:selected', fullnameSelectedHandler);
    }