I have populated Grid View Dynamically with json Data ..Button Column started to appears only in First Row ..But not in below rows ..
I have Tried Code to add column in server side code as well as in Mark Up ..I also search but could not able to find any thing relevant
this is my MarkUp :
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List.aspx/GetData",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#gvDetails").append("<tr><td>" + data.d[i].c1 + "</td><td>" + data.d[i].c2 + "</td><td>" + "</td></tr>");
}
},
error: function (result) {
alert(result.status + ' ' + result.statusText);
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" runat="server" ShowHeaderWhenEmpty="True">
<Columns>
<asp:ButtonField Text="Button" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
this is code behind :
protected void Page_Load(object sender, EventArgs e)
{
BindColumnToGridview();
}
private void BindColumnToGridview()
{
DataTable dt = new DataTable();
dt.Columns.Add("c1");
dt.Columns.Add("c2");
dt.Rows.Add();
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static tbl1[] GetData()
{
try
{
using (var context = new TestDBContext())
{
List<tbl1> lsTbl1 = new List<tbl1>();
lsTbl1 = (from c in context.tbl1 select c).ToList();
return lsTbl1.ToArray();
}
}
catch (Exception)
{
throw;
}
}
I also tried to add column from code behind
gvDetails.Columns.Add(new ButtonField() { Text = "Button" });
this is not working too
any sugestion will be helpful
Since gvDetails is a server side control you should use <%= gvDetails.ClientID %> in your JS snippet.
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "List.aspx/GetData",
data: "{}",
dataType: "json",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
$("#<%= gvDetails.ClientID %>").append("<tr><td>" + data.d[i].c1 + "</td><td>" + data.d[i].c2 + "</td><td>" + "</td></tr>");
}
},
error: function (result) {
alert(result.status + ' ' + result.statusText);
}
});
});
</script>
EDIT:
Related
I want to show an Alert Message Box When Selected Date is Match with Database Date on datetime picker.
Even though WebMethod is working fine, my code right now is everytime I select, alert message always come out without checking.
Test.aspx.cs
[System.Web.Services.WebMethod]
public static string GetDateFromDB(DateTime compareDate)
{
string selectedDate = compareDate.ToString("yyyy/MM/dd");
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginDBConnectionString1"].ConnectionString);
SqlCommand com = new SqlCommand("SELECT * from Holiday where Date='" + selectedDate + "'", conn);
SqlDataAdapter sqlDa = new SqlDataAdapter(com);
DataTable dt = new DataTable();
sqlDa.Fill(dt);
if (dt == null || dt.Rows.Count == 0)
return "NG";
else
return "OK";
}
Test.aspx
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date' id="datepicker" autocomplete="off">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
jQuery(function ($) {
$("#datepicker").datepicker({
onSelect: function (dateText) {
alert("Selected date: " + dateText + "; input's current value: " + this.value);
$(this).change();
$.ajax({
type: "POST",
url: "Test.aspx/GetDateFromDB",
data: '{ "compareDate" : "' + dateText + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
//success: OnSuccess,
//failure: function (response) {
// alert(response.d);
//}
});
},
}
).on("change", function () {
display("Got change event from field");
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
</script>
It alerts always because alert message is into onChange event.
You need to move this to on Success of AJAX call.
Below is edited code of yours.
Edit : Check condition as per return value from code behind (i.e "OK" & "NG").
<link href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<input type='text' class='date' id="datepicker" autocomplete="off">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
jQuery(function ($) {
$("#datepicker").datepicker({
onSelect: function (dateText) {
$(this).change();
$.ajax({
type: "POST",
url: "Test.aspx/GetDateFromDB",
data: '{ "compareDate" : "' + dateText + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
if(data == "OK")
{
alert("Selected date: " + dateText + "; input's current value: " + this.value);
}
},
//failure: function (response) {
// alert(response.d);
//}
});
},
}
).on("change", function () {
display("Got change event from field");
});
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
</script>
Note: Above changes is Non-Tested. Please write comment if its not working.
I am trying to implement this:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_progressbar_3
I tried to implement this first, but I don't know how to implement it. So tried to implement using jquery progressbar which I found some implementation examples online. I want the progress bar to be updated based on the code behind for loop.
I am new to front end development. Please help!
My aspx page:
<div id="progressbar"></div>
<div id="result"></div><br />
<asp:Button ID="btnGetData" runat="server" Text="Get Data" />
<script type="text/javascript">
$(document).ready(function () {
$$("progressbar").progressbar({ value: 0 });
$$('btnGetData').click(function () {
var intervalID = setInterval(updateProgress, 250);
$.ajax({
type: "POST",
url: "Default.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
//async: true,
success: function (data) {
debugger;
var test = parseInt(data.d);
$("#progressbar").progressbar("value", test);
$("#result").text(msg.d);
clearInterval(intervalID);
}
});
return false;
});
function updateProgress() {
var value = $("#progressbar").progressbar("option", "value");
if (value < 100) {
$("#progressbar").progressbar("value", value + 1);
}
}
});
</script>
CodeBehind:
[System.Web.Services.WebMethod]
public static object GetResult()
{
DataSet ds = new DataSet();
var Numbers = GetNumbers.Tables[0];
var count = 0;
foreach(int num in Numbers.Rows)
{
ds.Tables[0].Rows.Add(GetData());
count+1;
}
return count;
}
I'm trying to call $.ajax method to retrieve NORTHWND Employees details based on the search criteria. But, for some reason, country, and title variable are always returning null. I am not understanding where I am doing wrong.
Below is the clear explanation.
Below is the code in AjaxDemoRequestPage.aspx
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country = $("#txtCountry").val();
data.title = $("#txtTitle").val();
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
Below is the code in PostTarget.aspx.cs page. In this page, when debugging I am always getting country, and title as null.
public partial class PostTarget : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var country = Request.Form["country"];
var title = Request.Form["title"];
var db = new NORTHWNDEntities();
var emps = db.Employees
.Where(x => x.Country.Contains(country) || x.Title.Contains(title))
.Select(x => new EmployeeSearchResult
{
EmployeeID = x.EmployeeID,
FirstName = x.FirstName,
LastName = x.LastName
});
Response.Clear();
Response.Write(JsonConvert.SerializeObject(emps));
Response.Flush();
Response.End();
}
}
Can anyone please suggest me where I am doing wrong?
The contentType should be this:
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
My blunder mistake was that I never made call to $.ajax method. Below is the modified and working code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
$.ajax(data);
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
ID generated by ASP.NET will not same as you have given. this is the reason you are getting null value .
You can access ASP.NET control in javascript in this way.
document.getElementById('<%= txtCountry.ClientID %>').value
And also you can simple use html button instead of ASP.NET button for making ajax request.
Here is your updated code.
<form id="form1" runat="server">
<div>
Country:
<asp:TextBox ID="txtCountry" runat="server"></asp:TextBox>
Title:
<asp:TextBox ID="txtTitle" runat="server"></asp:TextBox>
<!-- <asp:Button ID="btnAjax" runat="server" Text="$.ajax()" />-->
<input type="button" id="btnAjax" value="$.ajax()"/>
<div id="container"></div>
</div>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAjax").click(function (evt) {
var data = {};
data.country =document.getElementById('<%= txtCountry.ClientID %>').value;
data.title = document.getElementById('<%= txtTitle.ClientID %>').value;
debugger;
$.ajax({
url: "PostTarget.aspx",
type: "POST",
data: data,
contentType: "x-www-form-urlencoded;charset=UTF-8",
dataType: "json",
success: SuccessfulAjaxResponse,
error: ErroticAjaxResponse
});
evt.preventDefault();
});
});
function SuccessfulAjaxResponse(results, status, jqXHR) {
$("#container").empty();
debugger;
for (var i = 0; i < results.length; i++) {
$("#container").append("<tr>" +
"<td>" + results[i].EmployeeID + "</td>" +
"<td>" + results[i].FirstName + "</td>" +
"<td>" + results[i].LastName + "</td>"
);
}
}
function ErroticAjaxResponse(jqXHR, status, error) {
alert("Error: " + error);
}
</script>
</form>
I have asp.net Gridview that have at least 15 rows with textbox by default example
aspx
<asp:GridView ID="gv_Others" runat="server" AutoGenerateColumns="false" CssClass="gvothers">
<Columns>
<asp:TemplateField >
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<ItemTemplate >
<asp:TextBox ID="txtEmp" runat="server" Width=100% Height=22px CssClass="txtE"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs (here how I am generating 15 rows of a GridView)
private void SetInitialRowsofOthers()
{
var list = new List<string>();
for (int i = 0; i < 16; i++)
{
list.Add(string.Empty);
}
gv_Others.DataSource = list;
gv_Others.DataBind();
gv_Others.HeaderRow.Visible = false;
}
WevService.axms
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<string> GetotherServices(string txt1)
{
// your code to query the database goes here
List<string> result = new List<string>();
string QueryString = System.Configuration.ConfigurationManager.ConnectionStrings["autoDBConn"].ToString();
using (SqlConnection obj_SqlConnection = new SqlConnection(QueryString))
{
using (SqlCommand obj_Sqlcommand = new SqlCommand("Select DISTINCT OtherService as txt1 from easy_tblOtherServiceMaster where OtherService like #SearchText + '%' ", obj_SqlConnection))
{
obj_SqlConnection.Open();
obj_Sqlcommand.Parameters.AddWithValue("#SearchText", txt1);
SqlDataReader obj_result1 = obj_Sqlcommand.ExecuteReader();
while (obj_result1.Read())
{
result.Add(obj_result1["txt1"].ToString().TrimEnd());
}
}
}
return result;
}
I want to fill each textbox by jQuery autocomplete.. for this I created a webservice and getting a value from jQuery.
How I am trying to achieve this task:
<script src="js/jquery-1.8.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
function SearchText() {
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
$($arrT).autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetotherServices",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt1' : '" + $($arrT).val() + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
}
});
</script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
function SearchText() {
$("#<%=Txt_RegNo.ClientID %>").autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt' : '" + $("#<%=Txt_RegNo.ClientID %>").val() + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
}
});
</script>
<script type="text/javascript">
$(function() {
$('input:text:first').focus();
var $inp = $('input:text');
$inp.bind('keydown', function(e) {
//var key = (e.keyCode ? e.keyCode : e.charCode);
var key = e.which;
if (key == 13) {
e.preventDefault();
var nxtIdx = $inp.index(this) + 1;
$(":input:text:eq(" + nxtIdx + ")").focus();
}
});
});
</script>
<script type="text/javascript">
function Load_OtherService() {
var hv = $('input[id$=hdnOthers]');
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
var hv1 = "" + hv.val();
var va = hv1.split(',');
for (var j = 0; j < va.length; j++) {
var $txt = $arrT[j];
$($txt).val(va[j]);
}
}
</script>
Now for example when I type "Engine Work" in TEXTBOX 1 and select the value which populated by jQuery autocomplete("Engine Work") then second time when I type in other text box (TEXT BOX 2). It's only give me the "Engine Work" option to select.. which means after selecting any value (populated by jQuery autocomplete) I can't select any other value in other text boxes....
Example:- (See Image Below)
as you see i type Genral Work but still it`s populating the Previous value "Engine Work" in jquery AutoComplete which i dont want
How to find the TextBox by CSS Class using jQuery????
Something like this (its only find TextBox id by using jQuery inside GridView but I need to find textbox by Css Class)
var $arrT = $('#<%=gv_Others.ClientID %>').find('input:text[id$="txtEmp"]');
Change your script block to this:
$(document).ready(function() {
// This selects all inputs inside the table with the txtE class and applies
// the autocomplete function to them
$('table[id$="gv_Others"] input.txtE').autocomplete({
source: function(request, response) {
$.ajax({
url: "WebService.asmx/GetAutoCompleteData",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ 'txt1' : '" + request.term + "'}",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
label: item,
value: item
}
}))
//debugger;
},
error: function(result) {
alert("Error");
}
});
},
minLength: 1,
delay: 1000
});
});
Look at the data: in the ajax post - it's using request.term and I changed the selector.
The issue with your jquery is this line:
data: "{ 'txt1' : '" + $($arrT).val() + "'}",
That will always return the first value of the array (the first textbox) so it's always submitting the first value to your webservice as the search text.
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace PlatForm_RollUp
{
/// <summary>
/// Summary description for SearchDPN
/// </summary>
public class SearchDPN : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string prefixText = context.Request.QueryString["term"];
if (string.IsNullOrEmpty(prefixText)) { prefixText = "NA"; }
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = ConfigurationManager
.ConnectionStrings["PPN_ConnectionString"].ConnectionString;
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select DPN_Key, DPN, Item_Desc from Customer.DIM.PPN WHERE " +
"DPN like #SearchText+'%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
//StringBuilder sb = new StringBuilder();
List<string> _dpn = new List<string>();
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
//sb.Append(string.Format("{0} - {1}", sdr["DPN"], sdr["Item_Desc"], Environment.NewLine));
_dpn.Add(sdr["DPN"].ToString() +" - " +sdr["Item_Desc"].ToString());
}
}
conn.Close();
context.Response.Write(new JavaScriptSerializer().Serialize(_dpn));
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
***************************
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
initializer();
});
var prmInstance = Sys.WebForms.PageRequestManager.getInstance();
prmInstance.add_endRequest(function () {
//you need to re-bind your jquery events here
initializer();
});
function initializer() {
$("[id*=txtDPN]").autocomplete({ source:
"/Handlers/SearchDPN.ashx" });
}
</script>
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
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
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:
Url of the fetching method,
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.
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
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;
}
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>