1

我的数据库表 TAGS(TagId,TagName) 我的 web 方法代码如下

 public List<Tag> FetchTagList(string tag)
{
    OleDbConnection cn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
    DataSet ds = new DataSet();
    DataTable dt = new DataTable();
    string query = "select * from TAGS Where TagName like '@myParameter'";
    OleDbCommand cmd = new OleDbCommand(query,cn);
    cmd.Parameters.AddWithValue("@myParameter", "%" + tag + "%");
    try
    {
        cn.Open();
        cmd.ExecuteNonQuery();
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        da.Fill(ds);
    }
    catch(OleDbException excp)
    {

    }
    finally
    {
        cn.Close();
    }
    dt = ds.Tables[0];

    List<Tag> Items = new List<Tag>();

    Tag obj;

    foreach (DataRow row in dt.Rows)
    {
        obj = new Tag();
        //String From DataBase(dbValues)
        obj.TagName = row["TagName"].ToString();
        obj.ID = Convert.ToInt32(row["TagId"].ToString());

        Items.Add(obj);
    }
    return Items;
} 

}

我用过课

公共类标签 { 公共 int ID { 获取;放; } 公共字符串 TagName { 获取;放; } }

我的 JavaScript 代码是

<link href="css/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="jsautocom/jquery.min.js" type="text/javascript"></script>
<script src="jsautocom/jquery-ui.min.js" type="text/javascript"></script><script type="text/javascript">
        $(function () {
            $(".tb").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "WebService.asmx/FetchTagList",
                        data: "{ 'tag': '" + request.term + "' }",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                    value: item.TagName
                                }
                            }))
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength: 1
            });
        });
    </script>

我的 aspx 页面就像

<div class="demo">
    <div class="ui-widget">
        <label for="tbAuto">Search Tag: </label>
          <asp:TextBox ID="TextBox1" class="tb" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
          <asp:Button ID="btnSearch" runat="server" CssClass="btnSearch" 
    onclick="btnSearch_Click" Text="Search"  />
    </div>
</div>

但我什么也没得到。如何解决它。非常感谢任何帮助我的人。在此先感谢

4

5 回答 5

2

只需更改 ajax 中的数据和响应,如下所示

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

dataType: "json",

success: function (data) {
    response(data.d);
},

error: function (result) {
    alert("Error");
}

在您的情况下,将 PhoneContactName 更改为标签等,

希望这会有所帮助:D

于 2012-10-23T10:23:48.017 回答
1

这里有两点需要注意:

A-确保您可以调用您的服务方法,在您的函数上使用 [WebMethod] 属性以使其可通过 http 调用。您可能还需要稍微调整 WebService 设置以使其正常工作。

B- 你的 javascript 代码对于这个任务来说太多了。考虑到 Autocomplete 官方文档中写的内容,您只需要指出 2 件事:

  1. 获取方法的 URL,
  2. 用户将要写入的控件,并将使用内部的当前值触发自动完成调用。

考虑以下示例:

$(".tb").autocomplete({source: "URL_OF_YOUR_REMOTE_METHOD"});

考虑到您的示例,您需要输入以下代码:

$(".tb").autocomplete({source: "WebService.asmx/FetchTagList"});

这是使其工作所需的最少代码段。但是像你一样手动处理所有事情有点复杂,而且一旦问题开始发生就不容易弄清楚我们的问题。

一个活生生的例子:http: //jsfiddle.net/grtWe/1/

只需使用这段代码并让我知道它是否有效,那么我们可以从这里开始实现您的目标。

于 2012-10-23T10:22:38.487 回答
1

如果 FetchTagList 是您从 jquery 调用的网络方法,那么不要从方法返回列表,您可以将数据表直接绑定到自动完成文本框,只需检查以下链接如何做到这一点。

http://nareshkamuni.blogspot.in/2012/06/sample-example-of-jquery-autocomplete.html

你也可以使用 ajax 自动完成扩展器来做到这一点。对于使用 ajax 自动完成扩展器,请参考以下链接

http://www.aspsnippets.com/Articles/ASPNet-AJAX-AutoCompleteExtender-Pass-Additional-Parameter-to-WebMethod-using-ContextKey.aspx

于 2012-10-23T10:36:22.817 回答
0

脚本如下:

<script type="text/javascript">
    $(document).ready(function () {
        SearchText();

    });
    function SearchText() {
        $(".auto").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Photos.aspx/GetAutoCompleteData",
                    data: "{'CategoryName':'" + document.getElementById("<%= txtCategory.ClientID %>").value + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error Occurred");
                    }
                });
            }
        });


    }
            </script>

网络方法:

[WebMethod]

public static List<string> GetAutoCompleteData(string CategoryName)
{
    List<string> result = new List<string>();
    OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"|DataDirectory|\\ImageDB2.mdb\";Persist Security Info=True");
    string query = "select TagName from TAGS where TagName LIKE '%" + CategoryName + "%'";
    OleDbCommand cmd = new OleDbCommand(query, con);
    con.Open();
    //cmd.Parameters.Add("@ptext", System.Data.SqlDbType.NVarChar).Value = CategoryName;
    OleDbDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        result.Add(dr["TagName"].ToString());
    }
    return result;


}
于 2013-10-01T07:44:48.397 回答
0

C# 代码

这里需要记住一件事,Json 数据我们不能手动创建,使用 JavaScriptSerializer 类创建

<%@ WebHandler Language="C#" Class="CountryStateCityHandler" %>

using System;
using System.Web;
using System.Data;
using System.Collections.Generic;

public class CountryStateCityHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.Request.QueryString["action"] != null)
{
string strCallbackFunf = string.Empty;

if (context.Request.QueryString["callback"] != null)
{
strCallbackFunf = Convert.ToString(context.Request.QueryString["callback"]).Trim();
}

if (context.Request.QueryString["action"] == "getcountry")
{                   
DataTable dt = GetDataTable("EXEC PR_GetCountries"); //GetDataTable need to write, this method will call the Database and get the result
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}

context.Response.ContentType = "text/plain";
if (string.IsNullOrEmpty(strCallbackFunf))
{
context.Response.Write(serializer.Serialize(rows));
}
else
{
context.Response.Write(strCallbackFunf+"("+serializer.Serialize(rows)+");");      
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}

//需要附上HTML CODE或.aspx代码和脚本。

<html>
<head>
<script src="../scripts/jquery-1.7.js"></script>
<link href="../scripts/jqueryui/development-bundle/themes/smoothness/minified/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../scripts/jqueryui/js/jquery-ui-1.10.4.custom.min.js"></script>
<link href="../scripts/jqueryui/development-bundle/demos/demos.css" rel="stylesheet"  type="text/css" />
<script language="JavaScript" type="text/javascript">     

    var CountriesTags; //Local variable to store json object

    $(function () {
        $("#lnkCountry")
          .attr("tabIndex", -1)
          .attr("title", "Show All Items")
          .button({
              icons: {
                  primary: "ui-icon-triangle-1-s"
              },
              text: false
          })
          .removeClass("ui-corner-all")
          .addClass("custom-combobox-toggle ui-corner-right")
          .click(function () {              
              var wasOpen = $("#Country").autocomplete("widget").is(":visible");
              $("#Country").autocomplete("widget").css("display", "none");
              if (wasOpen) {
                  $("#Country").autocomplete("widget").css("display", "none");
                  return;
              }
              // Pass empty string as value to search for, displaying all results
              $("#Country").autocomplete("search", "");
          }); 

        $("#Country").autocomplete({
            source: function( request, response) {
                var matcher = new RegExp("(^| )" + $.ui.autocomplete.escapeRegex(request.term), "i");
                response($.grep(CountriesTags, function (item) {
                    return matcher.test(item.label);
                }));
            },
            minLength: 0,
            select: function (event, ui) {
                var sv = ui.item.label;
                var res = $.grep(CountriesTags, function (e, i) {
                    return e.label == sv;
                });
                if (res.length == 0) {                    
                    this.value = "";
                    $("#CountryID").val("");
                    alert(sv + " country is not available in database.");
                }
                else {
                    $("#CountryID").val(res[0].id);
                }
            },
            change: function (event, ui) {
                var sv = this.value;
                var res = $.grep(CountriesTags, function (e, i) {
                    return e.label == sv;
                });
                if (res.length == 0) {                    
                    this.value = "";
                    $("#CountryID").val("");
                    alert(sv + " country is not available in database.");
                }
                else {
                    $("#CountryID").val(res[0].id);
                }
            },
        });
        LoadCountry();
    }

    //html inputs Value are country id (<%=CountryID %>) and country name (<%=Country%>)
    function LoadCountry() {
        $.ajax({
            url: "CountryStateCityHandler.ashx?action=getcountry",
            dataType: "jsonp",
            type: 'GET',
            async: false,
            success: function (data) {
                CountriesTags = data;
                //array of Json Object will return
                //label, value and id are keys
                //Example  id:219 label:"United States" value:"United States"
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status + ' - Method: Loading countries - ' + thrownError);
            }
        });
    }
</script>
</head>

<body>

<table border="0" cellspacing="0" cellpadding="0">
<tr>
    <td>        
        <input type="text" name="Country" id="Country" maxlength="50" size="20" class="TextBox" value="<%=Country%>" /> 
        <input type="hidden" id="CountryID"  name="CountryID"  value="<%=CountryID %>">
    </td>
    <td>
        <a style="height: 16px" id="lnkCountry"></a>
    </td>                                                
</tr>

</table>

</body>

</html>
于 2017-02-17T09:42:55.200 回答