简体   繁体   English

使用jquery在asp.net中自动完成

[英]Auto complete in asp.net using jquery

Here I'm trying to use jquery auto complete in asp.net, I'm trying to retrieve the data from sql data source and use that for auto fetch. 在这里我试图在asp.net中使用jquery auto complete,我正在尝试从sql数据源中检索数据并将其用于自动提取。 while I running the code auto complete have not worked. 而我运行代码自动完成没有工作。

my code 我的代码

<script src="jquery.min.js" type="text/javascript"></script>
    <script src="jquery-ui.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            SearchText();
        });
        function SearchText() {
            $(".autosuggest").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "Inventory.aspx/GetAutoCompleteData",
                        data: "{'username':'" + document.getElementById('txtPartno').value + "'}",
                        dataType: "json",
                        success: function (data) {
                            response(data.d);
                        },
                        error: function (result) {
                            alert("Error");
                        }
                    });
                }
            });
        }
</script>

textbox field 文本框字段

<asp:TextBox ID="txtPartno" CssClass="Textboxbase" class="autosuggest" runat="server"></asp:TextBox>

and my c# code 和我的c#代码

protected void Page_Load(object sender, EventArgs e)
{

}
[WebMethod]

public static List<string> GetAutoCompleteData(string username)
{
    List<string> result = new List<string>();
    using (SqlConnection con = new SqlConnection("Data Source=MYPC-GN\\KASPLDB;Integrated Security=False;User ID=sa;Password=*****;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False"))
    {
        using (SqlCommand cmd = new SqlCommand("select DISTINCT PART_NO from Inventory where UserName LIKE '%'+@SearchText+'%'", con))
        {
            con.Open();
            cmd.Parameters.AddWithValue("@SearchText", username);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                result.Add(dr["UserName"].ToString());
            }
            return result;
        }
    }
 }

One problem which I can see is your javascript call is little wrong. 我能看到的一个问题是你的javascript调用有点不对。 You cannot get the value of textbox which is created by asp itself with document.getElementById('txtPartNo') . 您无法使用document.getElementById('txtPartNo') asp本身创建的文本框的值。 To get this value, you will have to get it's client id which you can get using- txtPartNo.ClientID so finally this will become- 要获得此值,您必须获取它的客户端ID,您可以使用txtPartNo.ClientID以便最终这将成为 -

data: "{'username':'" + document.getElementById('<%= txtPartno.ClientID %>').value + "'}",

If you don't try this way then you will not get the actual value of that textbox and undefined will be sent to the C# method which will not return anything. 如果你不尝试这种方式,那么你将无法获得该文本框的实际值,并且undefined将被发送到C#方法,该方法不会返回任何内容。

First you should check if the JavaScript function it's getting called. 首先,您应该检查它是否被调用的JavaScript函数。 If it's getting called then you should check if the url is correct. 如果它被调用,那么你应该检查网址是否正确。 You can check in developer tools/ firebug etc. to see what request are you sending. 您可以检查开发人员工具/ firebug等,以查看您发送的请求。

I did as follows: 我做了如下:

ajaxCallSetting.js ajaxCallSetting.js

 var ajaxCallSetting = function (element, message, req) { var baseInfo = { baseUrl: "http://localhost:10266/" }; var buildUrl= function() { return baseInfo.baseUrl + message; }; var callApi = function(request, response) { $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: buildUrl(), data: JSON.stringify(req), dataType: "json" }).success(function(data) { response(data.d); }); }; return { init: function() { $(element).autocomplete({ source: callApi }); } }; }; 

The head tag: 头标记:

 <head> <title></title> <script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js" type="text/javascript"></script> <script src="ajaxCallSetting.js"></script> <link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" /> <script type="text/javascript"> $(document).ready(function () { var req = { username: $('#txtPartno').val() }; apiSettings('#txtPartno', "Default.aspx/GetAutoCompleteData", req).init(); }); </script> </head> 

As far as possible, Keeping separate Html code with the code in JavaScript is useful. 尽可能使用JavaScript中的代码保持单独的Html代码是有用的。

I don't think your TextBox is being hooked up properly. 我不认为你的TextBox正在被正确连接。 Try this: 尝试这个:

<asp:TextBox ID="txtPartno" CssClass="Textboxbase autosuggest" runat="server"></asp:TextBox>

And try this in your JavaScript: 并在您的JavaScript中尝试这个:

$(".autosuggest").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Inventory.aspx/GetAutoCompleteData",
                    data: "{'username':'" + request.term + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM