AutoCompleteExtender doesn't work - asp.net

I want to use AutoCompleteExtender
but it doesn't work ,i put a break point in the web service but it doesn't enter the web service !!
<asp:TextBox ID="txt_empName" runat="server" Width="300px" ></asp:TextBox>
<cc1:AutoCompleteExtender ID="txt_empName_AutoCompleteExtender" runat="server"
CompletionListCssClass="autocomplete_completionListElement" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem"
CompletionListItemCssClass="autocomplete_listItem" Enabled="True" MinimumPrefixLength="4"
OnClientItemSelected="get_emp_num" UseContextKey="True" ServiceMethod="Get_Emp_AutoComplete"
ServicePath="~/EmpAutoComplete.asmx" TargetControlID="txt_empName" BehaviorID="ACE_empName"
EnableCaching="False">
</cc1:AutoCompleteExtender>
My web service :
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 AutoComplete : System.Web.Services.WebService
{
[WebMethod]
public List<string> Get_Emp_AutoComplete(string prefixText, int count, string contextKey)
{
//split the string in the text box to get the department equivalent to the last prefix text entered in the textbox after ',' or ';'
string[] s = prefixText.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
if (s.Length > 0)
{
prefixText = s[s.Length - 1].Trim();//Last item in the array
}
List<string> Emp_List = Get_RequestEmp(prefixText, contextKey);
return Emp_List;
}
public static List<string> Get_RequestEmp(string prefixText, string contextKey)
{
prefixText = prefixText.Trim().Replace(' ', '%');
DBConnection ConnectionObj = new DBConnection(CMSession.GetSession("code", HttpContext.Current), false);
string cmdText = "SELECT emp_num , trim(name) FROM grrt5emp WHERE name LIKE '%" + prefixText + "%' ORDER BY name";
DataTable dt = ConnectionObj.Return_DataTable(cmdText);
List<string> Emp_List = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
//Returning key-value pair
Emp_List.Add(AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(dt.Rows[i][1].ToString(), dt.Rows[i][0].ToString()));
}
return Emp_List;
}
}
My AjaxToolkit version is :
3.0.30930.28736

This worked for me: https://www.c-sharpcorner.com/UploadFile/57a357/autocomplete-extender-in-Asp-Net/
I think you're just missing the asp:ScriptManager

Related

Ajaxtoolkit - Autocomplete dont do anything when i click

I have tried everything and nothing works, i have no clue now. I used an example, that used to work ones but dont anymore. I used this example
https://www.aspsnippets.com/Articles/AJAX-AutoCompleteExtender-Example-in-ASPNet.aspx
And download the ajaxtoolkit from here
https://www.devexpress.com/products/ajax-control-toolkit/
I have scriptmanager in the top of the page and it looks like this.
This is my code
Masterpage.master
<asp:TextBox ID="txtContactsSearch" aria-describedby="basic-addon2" class="form-control-header" placeholder="Søg her ..." runat="server"></asp:TextBox> <cc1:AutoCompleteExtender ServiceMethod="SearchCustomers" MinimumPrefixLength="2" ServicePath="MasterPage.master" CompletionInterval="100" EnableCaching="false" CompletionSetCount="10" TargetControlID="txtContactsSearch" ID="AutoCompleteExtender1" runat="server" FirstRowSelected = "false"></cc1:AutoCompleteExtender>
My codebehind
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> SearchCustomers(string prefixText, int count)
{
using (MySqlConnection conn = new MySqlConnection())
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["Connectionstring"].ConnectionString;
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.CommandText = "select Produktnavn from Produkter where " +
"Produktnavn like #SearchText + '%'";
cmd.Parameters.AddWithValue("#SearchText", prefixText);
cmd.Connection = conn;
conn.Open();
List<string> customers = new List<string>();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(sdr["Produktnavn"].ToString());
}
}
conn.Close();
return customers;
}
}
}

ajaxToolkit:CascadingDropDown got error

I want to create cascadingdropdown using ajaxtoolkit but having error.
since newer version of ajaxcontroltoolkit have remove ToolkitScriptManager, so i use scriptmanager
<ajaxToolkit:CascadingDropDown
ID="cdlOffice"
TargetControlID="DropDownList1"
PromptText="Select Office"
PromptValue=""
ServicePath="~/WebService1.asmx"
ServiceMethod="GetLocation"
runat="server"
Category="LocationId"
LoadingText="Loading..." />
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="DropDownList1" CssClass="col-md-2 control-label">Location</asp:Label>
<div class="col-md-10">
<asp:DropDownList id="DropDownList1" runat="server" class="select2-me" data-placeholder="--SELECT--" data-rule-required="true" style="width:250px;" />
</div>
</div>
and WebService1.asmx as follow
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 WebService1 : System.Web.Services.WebService
{
[WebMethod]
public CascadingDropDownNameValue[] GetLocation(string knownCategoryValues)
{
string query = "SELECT DISTINCT ITOFF_NAME, ITOFF_ID FROM ITOFF_TBL ORDER BY ITOFF_NAME";
List<CascadingDropDownNameValue> Location = GetData(query);
return Location.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] GetFloor(string knownCategoryValues)
{
string Location = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)["LocationId"];
string query = string.Format("SELECT ITOFF_LEVEL, ITOFF_ID FROM ITOFF_TBL WHERE ITOFF_NAME = {0}", Location);
List<CascadingDropDownNameValue> Floor = GetData(query);
return Floor.ToArray();
}
private List<CascadingDropDownNameValue> GetData(string query)
{
string conString = ConfigurationManager.ConnectionStrings["ITFORMConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
cmd.Connection = con;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
values.Add(new CascadingDropDownNameValue
{
name = reader[0].ToString(),
value = reader[1].ToString()
});
}
reader.Close();
con.Close();
return values;
}
}
}
}
i'm having error showing
Unhandled exception at line 6, column 97862 in
http://localhost:60461/Scripts/WebForms/MsAjax/MicrosoftAjax.js
0x800a138f - JavaScript runtime error: Unable to get property
'webServiceFailedNoMsg' of undefined or null reference
all the code i learn from googling. is there anything missing or did wrong?
Try removing the String Param 'knownCategoryValues' from you getLocation() web method definition:
[WebMethod]
public CascadingDropDownNameValue[] GetLocation()
{
string query = "SELECT DISTINCT ITOFF_NAME, ITOFF_ID FROM ITOFF_TBL ORDER BY ITOFF_NAME";
List<CascadingDropDownNameValue> Location = GetData(query);
return Location.ToArray();
}
And remove locationID property from the from the Cascading DropDown definition.
Or, if you are getting the locationID from another dropdown then leave it in and define it as the ParentControlID

Autocomplete in Ajax not working?

In Ajax, i am using autocompleteExender in my asp.net application, i write the service for that, when i run that service it is working fine, when i place autocompleteextender in asp.net page and assign properity for ajax autocompleteextender it is not working. this is my code service:
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
SqlConnection con=new SqlConnection
("server=******;database=Mydb;user id=***;password=****;");
string sql = "Select productname from F_Product
Where productname like '" + prefixText + "%'";
SqlDataAdapter da = new SqlDataAdapter(sql, con);
try
{
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr[0].ToString(), i);
i++;
}
return items;
}
catch
{
return null;
}
finally
{
con.Close();
}
and this is my ajax autocompleteextender code.
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" MinimumPrefixLength="2"
TargetControlID ="TextBox1" ServiceMethod="GetCompletionList"
ServicePath="~/Autocomplete.asmx"
runat="server">
</asp:AutoCompleteExtender>
<asp:TextBox ID="TextBox1" runat="server"
Width="213px"></asp:TextBox>
Try this out.
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
string sql = "Select productname from F_Product Where productname like #prefixText ";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["productname"].ToString(), i);
i++;
}
return items;
}
If you find it useful, please mark it as your answer else let me know...
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Web.Script.Services;
namespace YourProject
{
/// <summary>
/// Summary description for WebService
/// </summary>
// [ScriptService]
//[System.Web.Script.Services.ScriptService()]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 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
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public string[] GetCompletionList(string prefixText)
{
string sql = "Select productname from F_Product Where productname like #prefixText ";
SqlDataAdapter da = new SqlDataAdapter(sql, System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["productname"].ToString(), i);
i++;
}
return items;
}
}
}
If you find it useful, please mark it your answer else let me know...

Displaying image on a separate page

I have a image datatype which on click of a linkbutton needs to be displayed on a seperate page
aspx page
detail view:
<asp:TemplateField HeaderText="Evidence (if any)">
<ItemTemplate>
<asp:LinkButton ID="lbEvidence" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "Evidence").ToString() == String.Empty ? "None" : DataBinder.Eval(Container.DataItem, "Evidence")%>'
CommandName="Select" CommandArgument = '<%# DataBinder.Eval(Container.DataItem, "Complaint_Id") %>'> </asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
ImageHandler.ashx
<%# WebHandler Language="C#" Class="FMMadminModule.imageHandler" %>
using System;
using System.Web;
using System.Data;
using System.Web.SessionState;
namespace FMMadminModule
{
public class imageHandler : IHttpHandler, IReadOnlySessionState
{
DataTable dt;
int key;
byte[] imageOut;
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
HttpRequest request = context.Request;
context.Response.ContentType = "image/jpeg";
response.BufferOutput = false;
// get the key, the index into the DataTable
key = Convert.ToInt32(request.QueryString["Complaint_ID"]);
// Prepare the datatable to hold the SNo key and the jpeg image, which will be written out
dt = new DataTable();
dt = (DataTable)context.Session["dt"];
if (!dt.Rows[key]["Evidence"].Equals(null))
{
imageOut = (byte[])dt.Rows[key]["Evidence"];
response.OutputStream.Write(imageOut, 0, imageOut.Length);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
How would I display the image on a separate page?
This is how aspx.cs looks like
protected void dvResolveComplaint_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
DetailsViewRow row = dvResolveComplaint.Rows[5];
//String RowId = (e.NewSelectedIndex).ToString();
Type csType = this.GetType();
String strScript = "<script> ";
strScript += #"var newWindow = window.open('imageHandler.ashx?Complaint_ID=" + e.CommandArgument + #"', 'Evidence', ' height=450, center:yes, width=600, status=no, resizable= yes, menubar=no, toolbar=no, location=yes, scrollbars=no, status=no')";
strScript += "</script>";
ClientScript.RegisterClientScriptBlock(csType, "ViewEvidence", strScript);
dvResolveComplaint.Attributes.Add("OnClick", strScript);
}
}
this is way overcomplicated. You don't need the linkbutton at all, just write an anchor-wrapped image in your item template and call it a day, e.g.:
<img src='url_to_your_handler' alt='complaint image' />

autocomplete extender problem?

I am using autocomplete extender, i write a webservice the webservice is working fine when i run webservice. But when i run my aspx page it is not displaying any thing the autocomplete is not showing only text box is there. this is my code......
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class WebService : System.Web.Services.WebService
{
SqlConnection con;SqlDataAdapter da;
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string[] GetTitleInfo(string prefixText)
{
int count = 10;
string sqry = "select * from news_upload where newstitle like #prefixText";
da = new SqlDataAdapter(sqry, "server=localhost;database=tfcnew;user id=sa;password=sql123");
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 100).Value = prefixText + "%";
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["newstitle"].ToString (), i);
i++;
}
return items;
}
this is (above) service.
<asp:TextBox ID="txtcomplete" runat ="Server" ></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server" MinimumPrefixLength ="1" ServiceMethod ="GetSuggestions" ServicePath="~/WebService2.asmx" TargetControlID ="txtcomplete" >
</asp:AutoCompleteExtender>
This is aspx code..
can u help me. thank you.
Add "[System.Web.Script.Services.ScriptMethod]" before the class declaration
[System.Web.WebService(Namespace = "http://tempuri.org/")]
[System.Web.WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptMethod]
public class WebService : System.Web.Services.WebService {
...
...
...
if it is already in your code, You could check the service path. Use Fiddler or Firebug to see if there is an actual call to the service. if not working then set the servicepath from paga_Load event of your aspx page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack() Then
AutoCompleteExtender2.ServicePath = ResolveUrl("~/mywebservice.asmx")
End If
End Sub

Resources