My AJAX auto-complete function is not working with a user control but when I use it with a normal ASP.NET page it works fine:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText, string contextKey)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ERPConnection"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
string CmdText = "select name+ '-' + ' ['+CONVERT(VARCHAR, custid) +']'as name from ht_cust where name like #City+'%' and EmpID =#EmpId";
SqlCommand cmd = new SqlCommand(CmdText, con);
cmd.Parameters.AddWithValue("#City", prefixText);
cmd.Parameters.AddWithValue("#EmpId", contextKey);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<string> CityNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CityNames.Add(dt.Rows[i][0].ToString());
}
return CityNames;
}
aspx code
<asp:UpdatePanel ID="UpdatePanel7" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtCity" runat="server" UseContextKey="true" onkeyup="SetContextKey()" CssClass="input-1" Width="200px"></asp:TextBox>
<ajaxToolkit:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="txtCity" MinimumPrefixLength="1" EnableCaching="true" CompletionSetCount="1" CompletionInterval="1000" ServiceMethod="GetCity" UseContextKey="true" CompletionListCssClass="autocomplete_completionListElement">
</ajaxToolkit:AutoCompleteExtender>
</ContentTemplate>
</asp:UpdatePanel>
You cannot call a webmethod through a user control because it will be automatically rendered inside the page. Move your webmethod to your aspx page.
If you want the logic inside the controller then you can call it from aspx page but your webmethod needs to be in aspx page.
Example:
In aspx page:
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText, string contextKey)
{
return mycontrol.GetCity(prefixText, contextKey);
}
In your user control :
public static List<string> GetCity(string prefixText, string contextKey)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ERPConnection"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
string CmdText = "select name+ '-' + ' ['+CONVERT(VARCHAR, custid) +']'as name from ht_cust where name like #City+'%' and EmpID =#EmpId";
SqlCommand cmd = new SqlCommand(CmdText, con);
cmd.Parameters.AddWithValue("#City", prefixText);
cmd.Parameters.AddWithValue("#EmpId", contextKey);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<string> CityNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CityNames.Add(dt.Rows[i][0].ToString());
}
return CityNames;
}
Related
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;
}
}
}
My code is not working but when i use it with normal asp page it works fine.
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetCity(string prefixText, string contextKey)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ERPConnection"].ToString();
SqlConnection con = new SqlConnection(constr);
con.Open();
string CmdText = "select name+ '-' + ' ['+CONVERT(VARCHAR, custid) +']'as name from ht_cust where name like #City+'%' and EmpID =#EmpId";
SqlCommand cmd = new SqlCommand(CmdText, con);
cmd.Parameters.AddWithValue("#City", prefixText);
cmd.Parameters.AddWithValue("#EmpId", contextKey);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
List<string> CityNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
CityNames.Add(dt.Rows[i][0].ToString());
}
return CityNames;
}
ascx code
<asp:UpdatePanel ID="UpdatePanel7" runat="server">
<ContentTemplate>
<asp:TextBox ID="txtCity" runat="server" UseContextKey="true" onkeyup="SetContextKey()"
CssClass="input-1" Width="200px"></asp:TextBox>
<ajaxtoolkit:autocompleteextender id="AutoCompleteExtender1" runat="server" targetcontrolid="txtCity"
minimumprefixlength="1" enablecaching="true" completionsetcount="1" completioninterval="1000"
servicemethod="GetCity" usecontextkey="true" completionlistcssclass="autocomplete_completionListElement">
</ajaxtoolkit:autocompleteextender>
</ContentTemplate>
</asp:UpdatePanel>
i hopoe you have added attribute EnablePageMethods = "true" to your scriptmanager on page
and add attribute UpdateMode="Conditional" to your updatepanel
I am trying to use Autocomplete Extender in my Project but its not working and I am using Vs2008 .net framework 3.5
and also it gives me error for grid-view paging that source is not available
this my .aspx code
<asp:TextBox ID="txtsearch" runat="server" Width="158px" CssClass="text"
Height="22px" ontextchanged="txtsearch_TextChanged"/>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
ServiceMethod="GetFilterCategoryName" CompletionSetCount="1" CompletionInterval="10"
EnableCaching="true" MinimumPrefixLength="1" TargetControlID="txtsearch"
UseContextKey="true">
</cc1:AutoCompleteExtender>
this is my Axpx.cs code
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> GetFilterCategoryName(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("select Question from quick_search where Question like #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> answer = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
answer.Add(dt.Rows[i][1].ToString());
}
return answer;
}
Add a script Manager to the aspx file.
Try like this
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods = "true"></asp:ScriptManager>
<asp:TextBox ID="txtsearch" runat="server" Width="158px" CssClass="text" Height="22px" ontextchanged="txtsearch_TextChanged"/>
<cc1:AutoCompleteExtender ServiceMethod="GetFilterCategoryName"
MinimumPrefixLength="1"
CompletionInterval="0" EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtsearch"
ID="autoCompleteExtender1" runat="server" FirstRowSelected = "false">
</cc1:AutoCompleteExtender>
COde Behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> GetFilterCategoryName(string prefixText)
{
SqlConnection conn = new sqlConnection(ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString);
conn.Open();
SqlCommand cmd = new SqlCommand("select Question from quick_search where Question like #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
List<string> answer = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
answer.Add(dt.Rows[i][1].ToString());
}
return answer;
}
I am new to ASP.NET
Someone in this forum helped me how to get the dropdown list work wth user countrol and it is working.
In my user control file, VendorListControl.ascx, I have this code below. Please assume that the VendorListControl.ascx.cs works correctly, which is when I select a VendorName, it will fired "ddlVendor_SelectedIndexChanged" to refreshed the "ddlVendorBUList" dropdown list.
<%# Control Language="C#" AutoEventWireup="true" CodeFile="VendorListControl.ascx.cs" Inherits="MyNamespace.VendorListControl" %>
<asp:DropDownList runat="server" ID="ddlVendorList" onselectedindexchanged="ddlVendor_SelectedIndexChanged" AutoPostBack="True" />
<asp:DropDownList runat="server" ID="ddlVendorBUList" AutoPostBack="True" />
<asp:Label runat="server" ID="lblMessage" />
My VendorListControl.ascx.cs code:
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MyNamespace
{
public partial class VendorListControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillVendors();
}
}
protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
{
int VendorID = Convert.ToInt32(ddlVendorList.SelectedValue.ToString());
FillVendorBU(VendorID);
}
private void FillVendors()
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorID, VendorName FROM MDF_Vendor";
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd; ;
conn.Open();
dAdapter.Fill(objDs);
conn.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
this.ddlVendorList.DataSource = objDs.Tables[0];
this.ddlVendorList.DataTextField = "VendorName";
this.ddlVendorList.DataValueField = "VendorID";
this.ddlVendorList.DataBind();
this.ddlVendorList.Items.Insert(0, "-- Select --");
}
else
{
this.lblMessage.Text = "No Vendor Found";
}
}
private void FillVendorBU(int VendorID)
{
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = #VendorID";
cmd.Parameters.AddWithValue("#VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
ddlVendorBUList.DataSource = objDs.Tables[0];
ddlVendorBUList.DataTextField = "VendorBUName";
ddlVendorBUList.DataValueField = "VendorBUID";
ddlVendorBUList.DataBind();
ddlVendorBUList.Items.Insert(0, "--Select--");
}
else
{
lblMessage.Text = "No states found";
}
}
}
}
Next, in my CreateNewRecord.aspx page, I have this code to include both dropdown list from user control. And I can see the dropdown lists works properly.
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl runat="server" />
</td>
</tr>
The problem is related to the ID of those two dropdown lists. When I attemp to do the insert record, it seems not to detect the ID for "ddlVendorList" and "ddlVendorBUList" come from user control ascx page. Error " The name 'ddlVendorList' does not exist in the current context"
ExecuteInsert(ddlVendorList.SelectedItem.Text,
ddlVendorBUList.SelectedItem.Text,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
Response.Write("<b>Record was successfully added!</b>");
I know I am new to ASP.NET, so please help.
You can put two properties in your VendorListControl to get the ddlVendorList selectedItem text and the ddlVendorBUList selectedItem text.
In VendorListControl.ascx.cs :
public string GetDdlVendorListSelectedItemText
{
get { return this.ddlVendorList.text; }
}
public string GetDdlVendorBUListSelectedItemText
{
get { return this.ddlVendorBUList.text; }
}
Then from your page CreateNewRecord, you can access those properties. You just need to add an id to your control :
<%# Register TagPrefix="uc" TagName="VendorListControl" Src="Controls/VendorListControl.ascx" %>
// Some where in the form
<tr>
<td class="right" width="20%">Vendor Name:</td>
<td>
<uc:VendorListControl id="vendorListControl" runat="server" />
</td>
</tr>
And you can access your properties like this in CreateNewRecord.aspx.cs :
ExecuteInsert(this.vendorListControl.GetDdlVendorListSelectedItemText,
this.vendorListControl.GetDdlVendorBUListSelectedItemText,
MDFAmount.Text,
StartDate.Text,
EndDate.Text,
VendorQuarter.Text,
MDFName.Text,
MDFSummary.Text,
Status.SelectedItem.Text,
CreatedBy.Value
);
You define public property who return SelectedItem.Text in your UserControl.
User Control (Ascx)
public string YourValue
{
get
{
return ddlVendorList.SelectedItem.Text;
}
}
Page (Aspx)
You can use your public property : YourValue.
ExecuteInsert(YourValue,
....... );
Nota : if you wish set value, you define setter on your property
After your update add theses properties
public string YourDdlVendorListSelectedItemText
{
get
{
return this.ddlVendorList.text;
}
}
public string YourDdlVendorBUListSelectedItemText
{
get
{
return this.ddlVendorBUList.text;
}
}
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...