1

my database table TAGS(TagId,TagName) my web method code is as follows

 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;
} 

}

i used class

public class Tag { public int ID { get; set; } public string TagName { get; set; } }

my javascript code is

<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>

my aspx page is as like

<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>

but i get nothing.how to solve it.any one helps me is greatly appreciated.thanks in advance

6
  • If you debug the C# code, does your method get called? If you debug the Javascript, does success or error get hit? Commented Oct 23, 2012 at 10:10
  • What is coming in textStatus?? Commented Oct 23, 2012 at 10:10
  • 1
    Does FetchTagList method marked with WebMethod attribute? Commented Oct 23, 2012 at 10:12
  • 1
    if it is a webmethod , why there is now '[webmethod]' attribute nor a 'static' keyword Commented Oct 23, 2012 at 10:15
  • when i use static keyword i get only error javascript alert message Commented Oct 23, 2012 at 10:40

5 Answers 5

2

just change the data and response in the ajax as given below

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

dataType: "json",

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

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

in your case change the PhoneContactName as something like the tag etc.,

hope this helps :D

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

3 Comments

what is the replacement of ContactName.ClientID when i use this i get error that contactname does not exists in current contex
That contact name is the id of my asp:text box where auto text complete is seen
you can use your asp:text box id :D
1

There are 2 things to take care here:

A- make sure that you can call your service method, use [WebMethod] attribute over your function to make it available to be called over http. you may also need to tune the WebService settings a little to make it to work.

B- Your javascript code is too much for this task. considering what is written inside the official documentation of Autocomplete, you only need to point out 2 things:

  1. Url of the fetching method,
  2. The control that the user is going to write on, and will trigger the autocomplete call using the current value inside.

Consider the following example:

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

considering your example, you will need to put this code:

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

This is the minimal piece of code that you need in order to make it to work. but to take everything manually as you did, is a little bit complicated and not that easy to figure our problem once they start to happen.

a live example: http://jsfiddle.net/grtWe/1/

just use this piece of code and let me know if it works, then we may go from here to achieve your goal.

2 Comments

my webservice settings is as follows [WebService(Namespace = "tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { public WebService () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod]
According to the source he already added in his js function as source: function (request, response) { }, and he has given the url of the web service, so it actually redirects to that so that might not be the problem
1

if FetchTagList is your webmethod you are calling from jquery then don`t return list from method you can bind datatable directly to the autocomplete textbox just check following link how to do that.

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

also you can do that using ajax autocomplete extender. for using ajax autocomplete extender refer following link

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

Comments

0

script is as follows:

<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>

web method:

[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;


}

Comments

0

C# code

One thing need to remember here, Json data we cannot create manually, create using JavaScriptSerializer Class

<%@ 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 or .aspx code and script needs to be attached.

<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>

Comments

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.