ajaxToolkit:CascadingDropDown got error - asp.net

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

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

Ajax cascading dropdownlist is not working for webservices methods

Need to bind drop down value from another drop down value, web methods not
firing even after added web reference, not showing any error.
I am getting error *method 500.
I am using visual studio and I have asp.net application as one project and a web service as another project.I am using web service in my asp.net application.
There is some sort of problem im my web service code. But i am unable to debug continuosly from asp.net application to web service.
I put break point both in application and web service but break point not activated in web service and it shows me connection error.
How can i do this while hosting on localhost?
my country.aspx code
<form id="form1" runat="server">
<ajax:ToolkitScriptManager EnablePageMethods="true" ID="tsmcascading" runat="server">
</ajax:ToolkitScriptManager>
<div>
<div>
<asp:DropDownList ID="ddlstate" runat="server" AutoPostBack="true">
</asp:DropDownList>
<ajax:CascadingDropDown ID="cddstate" runat="server" ServicePath="~/cascadingdropdown.asmx"
Category="stateid" ServiceMethod="addstate" TargetControlID="ddlstate" PromptText="select state"
LoadingText="Loading...">
</ajax:CascadingDropDown>
</div>
</div>
<div>
<div>
<asp:DropDownList ID="ddlcity" runat="server">
</asp:DropDownList>
<ajax:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="ddlcity"
Category="stateid" ParentControlID="ddlstate" ServiceMethod="addcity" PromptText="select city"
ServicePath="~/cascadingdropdown.asmx" LoadingText="Loading...">
</ajax:CascadingDropDown>
</div>
</div>
</form>
my webservice code (.asmx)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AjaxControlToolkit;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections.Specialized;
/// <summary>
/// Summary description for cascadingdropdown
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]
// 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 cascadingdropdown : System.Web.Services.WebService
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["addcontact"].ToString());
public cascadingdropdown()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public CascadingDropDownNameValue[] addstate(string state, string city)
{
con.Open();
SqlCommand cmdstate = new SqlCommand("select stateid,statename from tblStates", con);
cmdstate.ExecuteNonQuery();
SqlDataAdapter dastate = new SqlDataAdapter(cmdstate);
DataSet dsstate = new DataSet();
dastate.Fill(dsstate);
con.Close();
List<CascadingDropDownNameValue> statesnames = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dsstate.Tables[0].Rows)
{
string stateid = dtrow["stateid"].ToString();
string statename = dtrow["statename"].ToString();
statesnames.Add(new CascadingDropDownNameValue(statename, stateid));
}
return statesnames.ToArray();
}
[WebMethod]
public CascadingDropDownNameValue[] addcity(string state, string city)
{
int stateid;
StringDictionary statedetails = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(state);
stateid = Convert.ToInt32(statedetails["state"]);
con.Open();
SqlCommand cmdcity = new SqlCommand("select cityid,stateid,cityname from tblcities where stateid=#stateid", con);
cmdcity.Parameters.AddWithValue("#stateid", stateid);
cmdcity.ExecuteNonQuery();
SqlDataAdapter dacity = new SqlDataAdapter(cmdcity);
DataSet dscity = new DataSet();
dacity.Fill(dscity);
con.Close();
List<CascadingDropDownNameValue> citynames = new List<CascadingDropDownNameValue>();
foreach (DataRow dtrow in dscity.Tables[0].Rows)
{
string cityid = dtrow["cityid"].ToString();
string cityname = dtrow["cityname"].ToString();
citynames.Add(new CascadingDropDownNameValue(cityid, cityname));
}
return citynames.ToArray();
}
}`
Try using the standard definition for functions used by AjaxControltoolkit cascading dropdown:
public CascadingDropDownNameValue[] addState(String knownCategoryValues, String category, String contextKey)
{
...
}
public CascadingDropDownNameValue[] addCity(String knownCategoryValues, String category, String contextKey)
{
...
}
Context key is not a mandatory parameter, you can ommit it if you do not need it.
I have totally the same problem, i found a "tutorial" and i tried to fit it with my own code, but i couldn't get it to work i was also getting method 500 errors.
Try use 100% of this websites code
http://www.aspdotnet-suresh.com/2011/01/introduction-here-i-will-explain-how-to.html
It worked for me, i just fitted some of the code at a time.

AutoCompleteExtender doesn't work

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

ASP.NET C# - Dropdown list by using User Control

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

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

Resources