My project requirement says we want to use CascadingDropDown, but we dont want to create the webservice. We just want to create a public method .
Any one has an idea of how to do this.
Any Answers???
My project requirement says we want to use CascadingDropDown, but we dont want to create the webservice. We just want to create a public method .
Any one has an idea of how to do this.
I'm using the AJAX CascadingDropDown extender inside a FormView's InsertItemTemplate.
Question: What is the correct way to save the CascadingDropDown 's selected value back to the database?
I've tried do it by setting the SelectedValue in the CascadingDropDown tag (not the DropDownList) like this:
SelectedValue='<%# Bind("SellerRegionId") %>'
However, when trying to save, this fails with error "Input string was not in a correct format."
I've been able to make it work by setting the Values dictionary in the FormView's ItemInserting() event handler, using the SelectedValue of the DropDownList control (not the extender), as follows:
e.Values["SellerRegionId"] = sellerRegionDropDownList.SelectedValue;
Is this the correct way to do this?
Thanks, in advance, for any help you can give.
Yes the latter should work and in my own opinion personally is more efficient.
Hi,
I'm trying ot make use of the CascadingDropdown control but I'm having trouble figuring out how to pass the parameters I need to populate the initial (top level) DropDownList
For example, I have the following DropdownLists:
Program
SubProgram
I want the cascade to occur on the SubProgram.
The problem lies in populating the Program DropDownList. I need to populate it based on a couple integer values (ProducerID and ProductID).
How do I specify these values for use in the webmethod? I can't find any examples where the webmethod that populates the Parent DropDownList isn't doing some simple query like getting all makes of a car.
Hi,
You can use contextKey to pass additional parameters to the webmethod that is responsible for filled the dropdownlist.
Please refer to this thread: http://forums.asp.net/p/1159991/1919729.aspx#1919729
Hi there, I'm in trouble with cascadingDropDownList extender.
I use webMethod to make connection to a SQL database, actually methods work fine and get results in XML form in test page. However, when I make call from the cascadingDropDownLists at the .aspx page, It only gets a "Method error 500"
Here is the code
---.ASPX---
<%@dotnet.itags.org.PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"EnableEventValidation="false" %>
<%@dotnet.itags.org.RegisterAssembly="AtlasControlToolkit"Namespace="AtlasControlToolkit"TagPrefix="atlasToolkit" %>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.1//EN""http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
<title>Untitled Page</title>
</head>
<body>
<formid="form1"runat="server">
<atlas:ScriptManagerID="ScriptManager1"runat="server"/>
<div>
<asp:DropDownListID="DropDownList1"runat="server">
</asp:DropDownList>
<asp:DropDownListID="DropDownList2"runat="server">
</asp:DropDownList>
<atlasToolkit:CascadingDropDownID="CascadingDropDown1"runat="server">
<atlasToolkit:CascadingDropDownProperties
TargetControlID="DropDownList1"
Category="MarkaTitle"
ServicePath="http://localhost:3631/CDDWebService/Service.asmx"
LoadingText="Please Wait..."
PromptText="Select a Marka..."
ServiceMethod="getMarka">
</atlasToolkit:CascadingDropDownProperties>
<atlasToolkit:CascadingDropDownProperties
TargetControlID="DropDownList2"
Category="ModelTitle"
ServicePath="http://localhost:3631/CDDWebService/Service.asmx"
ParentControlID="DropDownList1"
ServiceMethod="getModel"
PromptText="Select Model..."
LoadingText="Please Wait...">
</atlasToolkit:CascadingDropDownProperties>
</atlasToolkit:CascadingDropDown>
</div>
</form>
<scripttype="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<references>
</references>
<components>
</components>
</page>
</script>
</body>
</html>
/---.ASPX---
--WebService Codes--
using System;
using System.Web;
using System.Web.Services;
using System.Configuration;
using System.Web.Services.Protocols;
using AtlasControlToolkit;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
[WebService(Namespace ="http://Boss.com.tr/",Name="CDDWS")]
[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]
publicclassService : System.Web.Services.WebService
{
string myConnectionString =ConfigurationManager.ConnectionStrings["VehiclesConnectionString"].ToString();
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
publicCascadingDropDownNameValue[] getMarka(string knownCategoryValues,string category)
{
SqlConnection dbConnection =newSqlConnection(myConnectionString);
SqlDataAdapter myAdapter =newSqlDataAdapter("select * from MarkaTbl", dbConnection);
DataTable myTable =newDataTable();
try
{
myAdapter.Fill(myTable);
}
catch (Exception ex)
{
//throw ArgumentException("not valid");
}
List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();
foreach (DataRow drin myTable.Rows)
{
values.Add(newCascadingDropDownNameValue((string)dr["MarkaTitle"],dr["MarkaID"].ToString()));
}
return values.ToArray();
}
[WebMethod]
publicCascadingDropDownNameValue[] getModel(string knownCategoryValues,string category)
{
SqlConnection dbConnection =newSqlConnection(myConnectionString);
SqlDataAdapter myAdapter =newSqlDataAdapter("select * from ModelTbl", dbConnection);
DataTable myTable =newDataTable();
try
{
myAdapter.Fill(myTable);
}
catch (Exception ex)
{
}
List<CascadingDropDownNameValue> values =newList<CascadingDropDownNameValue>();
foreach (DataRow drin myTable.Rows)
{
values.Add(newCascadingDropDownNameValue((string)dr["ModelTitle"], dr["ModelID"].ToString()));
}
return values.ToArray();
}
}
/--WebService Codes--
One more question; I couldn't understand exactly what is "category", and what it is stands for. I considered it is as fieldName of at the database :)
Thanks for any help ...
At least, can someone tell me what is "category" in CascadingDropDown extender ?
Hi BossDida,
You're getting a message returned by the ASP.NET AJAX Extensions indicating "there was a problem with your web service." I'd take a look at the CascadingDropDown.aspx sample page to see how what you're doing differs from it.
Also, the category (as described in the CascadingDropDown sample page) is used to indicate to the web service which drop down is asking for data (because you can have all your drop downs hit the same webmethod if you wanted).
Thanks,
Ted
Hi,
I am trying to use a CascadingDropDown list, the ParentDropDownList show up correctly, however, the Childdropdownlist give an error:
ChildDropDownList contains:
Prompt text
[Method error 500]
Here is the code I used:
<asp:ScriptManagerID="ScriptManager1"runat="server">
</asp:ScriptManager>
<br/>
<asp:DropDownListID="DropDownListLevel6xx"runat="server"
DataSourceID="ods_Level6"
DataTextField="LEVEL6"
DataValueField="LEVEL6"Width="126px"
>
</asp:DropDownList>
<asp:DropDownListID="DropDownListLevel7xx"
runat="server"Width="153px"
>
</asp:DropDownList>
<br/>
<br/>
<br/>
<asp:ObjectDataSource
ID="ods_Level6"
OldValuesParameterFormatString="original_{0}"SelectMethod="GetAllLevel6"
runat="server"
TypeName="DayOnePLCS.dsLevel67TableAdapters.Hierarchy_Level72TableAdapter"
></asp:ObjectDataSource>
<ajaxToolkit:CascadingDropDownID="CascadingDropDown1"runat="server"
Category="LEVEL7"LoadingText="Please wait..."ParentControlID="DropDownListLevel6xx"PromptText="Select a level 6 filter"
TargetControlID="DropDownListLevel7xx"ServicePath="Level67Service.asmx"
ServiceMethod="GetLevel7ByLevel6Id"/>
And the web service:
[WebService(Namespace ="http://tempuri.org/")]
[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]publicclassLevel67Service : System.Web.Services.WebService {
[WebMethod]publicCascadingDropDownNameValue[] GetLevel7ByLevel6Id(string knownCategoryValues,string category) {
string[] _categoryValues = knownCategoryValues.Split(':',';');
String _level6 =Convert.ToString(_categoryValues[1]);List<CascadingDropDownNameValue> _level7list =newList<CascadingDropDownNameValue>();
DayOnePLCS.dsLevel67TableAdapters.Hierarchy_Level71TableAdapter _level7Adapter =new DayOnePLCS.dsLevel67TableAdapters.Hierarchy_Level71TableAdapter();foreach (DataRow _rowin _level7Adapter.GetLevel7byLevel6(_level6)) {
_level7list.Add(newCascadingDropDownNameValue(_row["LEVEL7"].ToString(), _row["LEVEL7"].ToString()));}
return _level7list.ToArray();
}
}
I have tested the web service, it produce the right result.
Thanks in advance for any help!
Not sure if this will help, this is the web.config file..
Any help will be very much appreciated...
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
</sectionGroup>
</sectionGroup>
</sectionGroup>
</configSections>
<connectionStrings>
<REMOVED for sercurity reason>
</connectionStrings>
<system.web>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true">
<assemblies>
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
<add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Windows" />
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
-->
<globalization culture="en-GB"
fileEncoding="utf-8"
requestEncoding="utf-8"
responseEncoding="utf-8"/>
<pages>
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</controls>
</pages>
<httpHandlers>
<remove verb="*" path="*.asmx"/>
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
</httpHandlers>
<httpModules>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</modules>
<handlers>
<remove name="WebServiceHandlerFactory-Integrated"/>
<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</handlers>
</system.webServer>
</configuration>
Hi,
Error with status code 500 indicates that there is a problem when theserver tries to process the request. There can be variant causes. Any exceptioncould be a candidate. So the problem is mainly about how to find out the realcause of the error. Here are several options:
1. Set a break point in the code that is responsible for process therequest, then debug through it to find out the exception being thrown;
2. The real error message is usually returned in the response. We can useHttp Sniffer (e.g., Fiddler) to peek into the traffic between the client andserver to find out the error message.
Then it won't betoo difficult to solve it after the cause is known.
I tried to find an answer to this problem by searching through the site; however, I gave up after plowing through eleven pages returned from the forums, especially since there were 3,604 entries. Anyway, here goes...
I'm working on a website and want to use the CascadingDropDownList extender going against some tables in SQL Server 2005. I've found some C# code that'd do the trick, but my current employer uses only VB .Net, so I'm stuck with it. The problem occurs inside the Web Service function when I attempt to return the results from my Web Service to my form. The code is as follows:
<WebMethod()> _While dr.Read()
entities.Add(New CascadingDropDownNameValue(dr("EntityTypeID"), dr("EntityType")))
EndWhile
EndFunction
Has anyone done this in VB? If so, what am I doing wrong? If you have any code you could share, that'd also be greatly appreciated!
What is the error that you get?
If I try just returning entities, I get:
Value of type 'System.Collections.Generic.List(Of AjaxControlToolkit.CascadingDropDownNameValue)' cannot be converted to 'AjaxControlToolkit.CascadingDropDownNameValue'.
If I try returning entities.ToArray(), I get:
Value of type '1-dimensional array of AjaxControlToolkit.CascadingDropDownNameValue' cannot be converted to 'AjaxControlToolkit.CascadingDropDownNameValue'.
From what I've seen in the C# version, they're creating a List<T> of CascadingDropDownNameValue, along the line of
List<CascadingDropDownNameValue> entities = new List<CascadingDropDownNameValue>()
thus my attempt to use the line
Dim entitiesAs Generic.List(Of CascadingDropDownNameValue) =New Generic.List(Of CascadingDropDownNameValue)
It looks like I've finally found the answer! I declared entities thusly:
Dim entites = new Generic.List(Of CascadingDropDownNameValue)()
and the project compiled. Whether it runs or not remains to be seen.
Nope, now I'm getting a System.InvalidCastException: Unable to cast object of type 'System.Collections.Generic.List`1[AjaxControlToolkit.CascadingDropDownNameValue]' to type 'AjaxControlToolkit.CascadingDropDownNameValue'.
I wish I could do this in C# since I've been using it the last three years after having programmed in VB.NET the previous two, but I can't since the company is using VB.NET on all of it's Web development.
The problem is in the declaration of the function. You are returning the right thing List<CascadingDropDownNameValue> (in C#) but this is not what you define in the function declaration.
You need to change it to as List(Of CascadingDropDownNameValue)
Public Function GetEntityTypes(ByVal valuesAs String,ByVal idAs Integer)As AjaxControlToolkit.CascadingDropDownNameValue
Becomes
Public Function GetEntityTypes(ByVal valuesAs String,ByVal idAs Integer)As List(Of AjaxControlToolkit.CascadingDropDownNameValue)
HTH,
Jonathan.
I changed the included sample test page to remove the autopostback from theDropDownList3 dropdown (for color). I also removed the server side onselectedindxchanged eventhandler. I wanted to give the feedback to the user all from the client side. For that effect I added the following javascript code at the end of the page:
<script type="text/javascript">$addHandler($get('<%=DropDownList3.ClientID%>'), "change", ProvideFeedback);function ProvideFeedback(eventElement){var makeDropdown = $get('<%=DropDownList1.ClientID%>');var modelDropdown = $get('<%=DropDownList2.ClientID%>');var colorDropdown = $get('<%=DropDownList3.ClientID%>');if(colorDropdown.selectedIndex == 0){alert("Please make all your selections");}else{alert('You selected ' + makeDropdown.options[makeDropdown.selectedIndex].text + ' - ' + modelDropdown.options[modelDropdown.selectedIndex].text + ' - ' + colorDropdown.options[colorDropdown.selectedIndex].text);}} </script> It works just fine when I change the values in the color dropdown; I get the feedback. But I am also expecting to get the feedback when I change the make or model dropdown as the onchage is internally fired for color dropdown. But I never see that handled. Everytime I change values of make or model I never get the feedback.
Why is that? What am I missing?
Thanks.
Bumping up. Could someone please respond to this thread.
Ifthis.get_element().fireEvent('onchange'); is not producing the effect I am looking for what is it for?
Thanks.
Hi Nkv321,
CascadingDropDown will compare the selected value when its onchange event is fired. If no changes , there will no further actions , so it won't call the WebService.
I hope this helps.
Best regards,
Jonathan
It's not about changing the selected value and calling the web service. It's about when the parent value changes -- child drop down items get rebound -- and then an event is fired indicating that the child dropdown value has changed.
My question is what can that event be used for? How can it be used? I tried to use it in the sample that I put forth earlier but it was not executing. For example how can I add/attach a hanlder in the page to this event?
Thanks
Hi Nkv321,
I think you can attach a Javascript to the CascadingDropDown's add_selectionChanged or add_populated. For example:
function pageLoad(){$find("CascadingDropDown's BehaviorID"). add_selectionChanged(onSelectionChanged); }
function onSelectionChanged(){//your codes here.}
add_selectionChanged //Add an event handler for the selectionChanged event
add_populated //Add an event handler for the populated event
I Hope this help.
Best regards,
Jonathan
I have created a ModalPopupExtender that contains 3 CascadingDropDownLists. The dropdowns work and are populated normally if I don't try and set a value. If I try and set a value for the first dropdown I get an ArgumentOutOfRangeException error. It seems like the value is trying to be set before the dropdown is populated. Does anyone know how I can fix this?
Thanks.
Nevermind. I got it.
How to use CascadingDropDownLists bound to a MySQL-database? I want a parent DDList with items selected from one table and a second DDlist with items selected from another table based on the value selected in the first one. But how to write the asmx-file?
Hi,
First, you can refer to this documentation for how to use it with a database. http://ajax.asp.net/ajaxtoolkit/Walkthrough/CCDWithDB.aspx
Then, as far as I know, MySql provides db driver for .net which can be used in a similar way as the build-in ADO.NET does. You can download it from their website and try to implement it according to the above documentation.
Hope this helps.
Still trying to get these dropdowns to work. I have created a page with a single ddl that should be populated from the web service and has no parents but I still get the [method error 500] as the values, what am I mising here?
ddl.aspx
<%@dotnet.itags.org. Page Language="VB" AutoEventWireup="false" %>
<%@dotnet.itags.org. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<%@dotnet.itags.org. Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager id="ScriptManager1" runat="server" EnablePartialRendering="true" >
</asp:ScriptManager>
<asp:DropDownList ID="Region" runat="server" >
</asp:DropDownList>
<cc1:CascadingDropDown
Category="Region"
Enabled="true"
PromptText="Please work..."
ID="CascadingDropDown2"
TargetControlID="Region"
ServiceMethod="GetCountries"
ServicePath="CountriesByRegion.asmx"
runat="server">
</cc1:CascadingDropDown>
</form>
</body>
</html>
CountriesByRegion.asmx
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports PFCEnergy.Refining.Country.Business
Imports System.Data
Imports AjaxControlToolkit
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class CountriesByRegion
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Shared Function GetCountries(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim values As New _
System.Collections.Generic.List( _
Of AjaxControlToolkit.CascadingDropDownNameValue)
values.Add(New CascadingDropDownNameValue("foo", "bar"))
values.Add(New CascadingDropDownNameValue("bar", "foo"))
Return values.ToArray
End Function
End Class
Hi,
I too get the same error . Have you sorted the problem ?
Pls help if its working for u .
Thanks.
Yeah got it working, I added the bold and removed the struck through. Good luck.
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections.Generic
Imports System.Data
Imports AjaxControlToolkit
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<System.Web.Script.Services.ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class CountriesByRegion
Inherits System.Web.Services.WebService
<WebMethod()> _
PublicShared Function GetCountries(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim values As New _
System.Collections.Generic.List( _
Of AjaxControlToolkit.CascadingDropDownNameValue)
values.Add(New CascadingDropDownNameValue("foo", "bar"))
values.Add(New CascadingDropDownNameValue("bar", "foo"))
Return values.ToArray
End Function
End Class
Hi,
Iam not using list as u did in web method, So i thinkImports System.Collections.Generic is not needed.
Then i am not using Static (C#) in function.
So what would be wrong in my case?
Thanks.
Hi everyone, I had the same problem and after a little tweaking it works!
Here is the tip:
Please make that the database datatype matches the .NET datatype.If you have a different datatype in your database, you should TYPE CAST it to the corresponding .NET type.
string make = (string)dr["Make"];
int makeId = (int)dr["MakeID"];
.NET Framework Type
ADO.NET Database Type
SQL Data Type
String
Varchar
Varchar()
String
Nvarchar
Nvarchar()
String
NChar
Nchar()
String
NText
NText
String
Text
Text
Double
BigInt
Float
DateTime
DateTime
Datetime
DateTime
SmallDateTime
Smalldatetime
Int
Int
Int
Int64
BigInt
Bigint
Int16
SmallInt
smallint
Byte[]
Binary
Binary()
Byte[]
Image
Image
Byte[]
VarBinary
Varbinary()
Byte
TinyInt
Tinyint
Bool
Bit
Bit
Decimal
Decimal
Decimal
Decimal
Money
Money
Decimal
SmallMoney
SmallMoney
Float
Float
Float
Guid
UniqueIdentifier
Uniqueidentifier
Real
Real
Real
Hello,
My CascadingDropDownList gives me Method 500 error when more than 765 items are returned from the webservice! Is there a way to fix this? Thanks..
Hi,
that's probably related with the limit for the max size of the JSON payload set by ASP.NET AJAX. You can change it in the web.config:
<jsonSerialization maxJsonLength="500" />
Hi,
it must be added inside the configuration -> system.web.extensions -> scripting -> webServices section.
Hi,
I have changed the web config maxJsonLength to 1000. But i dont have that many values. First dropdown is giving me a value but on the second dropdown I am getting method error 500. My webservice code is as follows.
Imports
System.Web<WebService(Namespace:=
"http://tempuri.org/")> _Public
Class MIServiceMy code for aspx file is:
<%
@.PageLanguage="VB"AutoEventWireup="true"CodeFile="Default.aspx.vb"Inherits="_Default"EnableEventValidation="False"%><
htmlxmlns="http://www.w3.org/1999/xhtml">
Hi,
I have changed the web config maxJsonLength to 1000. But i dont have that many values. First dropdown is giving me a value but on the second dropdown I am getting method error 500. My webservice code is as follows.
Imports
System.Web<WebService(Namespace:=
"http://tempuri.org/")> _Public
Class MIServiceMy code for aspx file is:
<%
@.PageLanguage="VB"AutoEventWireup="true"CodeFile="Default.aspx.vb"Inherits="_Default"EnableEventValidation="False"%><
htmlxmlns="http://www.w3.org/1999/xhtml">Thank You,
Nepalaya
Hi,
what's the content of the 500? You can useFiddler to examine it.
I hope u get it the way you want, but 765 items in a drop down list isn't very user friendly? Think about screen res?
Maybe test out autocomplete control?
Just giving my view, but if you want 1000 items in a drop down list, go for it :P (I know how annoying it is when people try to divert you from the solution you want, so go for what is best in your app, just throwing out a suggestion)
Hi,
The problem resolved. It was not related with the lenght. Page method was not working so change the service method name to GetDropDownContents and it works.
<
cc1:CascadingDropDownID="CascadingDropDown1"runat="server"Category="city"LoadingText="[loading City...]"PromptText="Please select a city."ServiceMethod="GetDropDownContents"ServicePath="MIService.asmx"TargetControlID="DropDownList1">Thanks,
Nepalaya
Hello freinds,
I am not able to fill the cascading drop down using database. Does any one have fill it with the database??
Please help me i am stuck with this problem.
Thaks in advance.
Hi,
I get method error 500 in dropdownlist1 . Iam using WEB SERVICE .
i used <jsonSerializationmaxJsonLength="500" /> in web.config but still i get the error.
Can any one help ?
Thanks
Hey,
Trying to get my head round these CascadingDropDownLists but i am continually returned with a [Method Error 500] error.
This is my code for 'Default.aspx'
<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %
<%@dotnet.itags.org. Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server"
Category="Author"
TargetControlID="DropDownList1"
ServiceMethod="FillMe"
ServicePath="WebService.asmx"
PromptText="Please select a category"
>
</ajaxToolkit:CascadingDropDown>
</form>
</body>
</html>
And my webservice, WebService.asmx, is as follows:
using System;using System.Configuration;using System.Web;using System.Collections;using System.Collections.Generic;using System.Collections.Specialized;using System.Web.Services;using System.Web.Services.Protocols;using AjaxControlToolkit;using System.Data;using System.Data.SqlClient;/// <summary>/// Summary description for WebService/// </summary>[WebService(Namespace ="http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]public class WebService : System.Web.Services.WebService { [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static CascadingDropDownNameValue[] FillMe(string knownCategoryValues, string category) { string connString = ConfigurationManager.ConnectionStrings["tenderlistDB"].ConnectionString; SqlConnection conn = new SqlConnection(connString); DataTable dt = new DataTable(); string Sql = "SELECT [ID], [Name] FROM tblCategories WHERE ParentID=@dotnet.itags.org.ParentID ORDER BY [Name] ASC"; try { conn.Open(); SqlCommand comm = new SqlCommand(Sql, conn); comm.Parameters.AddWithValue("@dotnet.itags.org.ParentID", "0"); SqlDataAdapter adapt = new SqlDataAdapter(comm); adapt.Fill(dt); } finally { conn.Close(); } List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>(); for (int i = 0; i < dt.Rows.Count; i++) { CascadingDropDownNameValue CCD = new CascadingDropDownNameValue(); CCD.name = dt.Rows[i]["Name"].ToString(); CCD.value = dt.Rows[i]["ID"].ToString(); values.Add(CCD); }return values.ToArray(); }}
Anyone have an idea as to why it's just not working?
Cheers,
Sean
Most likely you have an exception being thrown in your WebMethod. Set a breakpoint in it and use the site in Debug mode. Step through the WebMethod and see if you are getting an exception. This is usually the case for me. The other thing I have seen is too much information being returned, but I think that is another error number. The Execption will not be returned by the Web Service, so AJAX throws a 500 error up at you.
Thanks for getting back to me.
I've never really used the debug function, but i stuck some breakpoints in the code and hit F5, and it all ran ok.
If i run it in debug mode, instead of Error method 500, i get an Error Method 12031...Could that be anything?
In terms of the SQL, it returns 12 rows when run through Sql Query Analyzer.
Appreciate your help!
Been thinking about this a little over lunch. Have you marked your Web Service and Web methods with AJAX attributes?
The Class should have this attribute:
<System.Web.Script.Services.ScriptService()> _
The Web Method this one:
<System.Web.Script.Services.ScriptMethod()> _
So a method would resemble the following:
<WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
PublicFunction GetMarkets(ByVal knownCategoryValuesAsString, _ByVal categoryAsString)As AjaxControlToolkit.CascadingDropDownNameValue()
Dim kvAs StringDictionary = _AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim RegionIdAsInteger
IfNot kv.ContainsKey("Region")OrElseNot Int32.TryParse(kv("Region"), RegionId)Then
ReturnNothing
EndIf
Dim lcAsNew LocMarketControllerDim itemListAs LocMarketList = lc.GetLocMarketByRegion(RegionId)
Dim valueAsNew List(Of AjaxControlToolkit.CascadingDropDownNameValue)ForEach itemAs LocMarketInfoIn itemList
value.Add(New AjaxControlToolkit.CascadingDropDownNameValue(item.Market, item.MarketId))Next
Return value.ToArrayEndFunction
Hey,
Tried that but still no joy. Starting to get frustrating now hehe, anyone else got any ideas?
Cheers for the help!
Hey,
Just to let you all know i got it working...i rewrote it this morning when i got into work and its all working fine...not sure why though, i have a feeling I wasn't passing through the correct parameters, so when the
'StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);'
line was hit, the method would break!
Thanks for all the help.
I am using several Cascading Drop Down Lists.
Is there a way that I can add values to the knownCategoryValues and category parameters that get passed to the webmethods?
For example:
[
WebMethod(EnableSession =true)] int Location_ID;
if (!kv.ContainsKey("Location") || !int.TryParse(kv["Location"],out Location_ID))
{
returnnull;
}
Sorry for the badly formatted code, but the Code Entry thing is not working.
Anyway, how would I add a "Key" of Location to the parameters? Would this have to be in the WebService, or can I add it from the web page?
Any help on this would be greatly appreciated!
Try to take a look at the following link about how to useAjax:CascadingDropDown with a Database for reference.Hi all,
I just found out that if I put a cascadingDropDownList with some dropDownLists, that have the OnSelectedIndexChanged event, inside a FormView, that event doesn't fire at the first time for the first dropdownlist.
This code works fine:
Ilha:But if I put it inside an InsertItemTemplate of a FormView, when I change the selected index of the first DDL at the first time, it doesn't go to theddlIlhas_SelectedIndexChanged handler. Anyone has any idea of what is going on here?Hi i am having exactly the same problem. I've been investigating this problem and it only seems to happen when used within the FormView. I'm quite new to the ajax control toolkit but if i find a solution i will let you know. Hope this helps.
<asp:DropDownList ID="ddlIlhas" runat="server" OnSelectedIndexChanged="ddlIlhas_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<br /
Concelho:
<asp:DropDownList ID="ddlConcelhos" runat="server" OnSelectedIndexChanged="ddlConcelhos_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<br /
<atlasToolkit:CascadingDropDown ID="ddlPanel" runat="server">
<atlasToolkit:CascadingDropDownProperties ID="propIlha" Category="Ilha" LoadingText="[A carregar...]" PromptText="Escolher..." ServiceMethod="GetIlhas" TargetControlID="ddlIlhas" ServicePath="/EDA.SGI.Website/WebService.asmx" />
<atlasToolkit:CascadingDropDownProperties ID="propConcelho" Category="Concelho" LoadingText="[A carregar...]" ParentControlID="ddlIlhas" PromptText="Escolher..." ServiceMethod="GetConcelhosByIlha" ServicePath="/EDA.SGI.Website/WebService.asmx" TargetControlID="ddlConcelhos" />
</atlasToolkit:CascadingDropDown>
</InsertItemTemplate>
Hi i am using the latest build and the problem still exists. I have uploaded the sample website with a few additions to show you:
http://www.flixon.com/AjaxControlToolkit.rar
Within the CascadingDropDown folder in the sample website there's now two new files:
Test.aspx - Without FormView (SelectedIndexChanged works fine)
Test2.aspx - With FormView (SelectedIndexChanged doesn't fire on first change)
Appreciate if you could help. Thanks
Sorry, I haven't managed to track this down all the way and I've run out of time just now. It definitely seems to be related to CascadingDropDown somehow since adding a plain DropDownList doesn't show the problem. I've tried commenting out the two event handlers in CascadingDropDownBehavior, but that didn't seem to do the trick. A quick web search turned up the following two articles which seem like they may provide a clue:
http://www.mikepope.com/blog/displayblog.aspx?permalink=1629
http://www.manuelabadia.com/blog/PermaLink,guid,a2abee08-bb7f-4fe5-8a24-6e56da99172a.aspx
If nothing else, pleaseopen a work item to track this bug. Thank you!
Hi, i added a work item a few weeks back:
http://www.codeplex.com/AtlasControlToolkit/WorkItem/View.aspx?WorkItemId=9454
Nothing has been posted yet. I will take a look at the posts you provided hopefully later today. Thanks for your help.
FYI, I just updatedwork item 9454 with the following notes:
Ted and I looked into this some just now. What appears to ultimately be the problem is that CascadingDropDown (and, in fact, ExtenderBase from which it derives) isn't seeing its CascadingDropDown_ClientStateValuesLoaded/Page_PreLoad method getting called when placed in a FormView's template. That ends up causing some different behavior due to the contents of the DropDownList being empty at first. The following page goes into some more detail about how the page lifecycle is different within a template and so this is probably a more general issue we should review for the Toolkit as a whole:http://msdn2.microsoft.com/en-us/library/ms178472.aspx.
What's good is that adding the following as the contents of the DropDownList seems to work around the problem for now (it's an empty ListItem that'll get replaced by CascadingDropDown once it populates the list): "<asp:ListItem></asp:ListItem>". With that, the sample code in Test2.aspx in the RAR fromhttp://forums.asp.net/thread/1671609.aspx works as expected.
Hi David
Thanks for your attention with this problem thus far. I am having a similar problem to this, but wherever I search, I get redirected back to this posting, so I'm adding my comments here. I am trying to use a set of 4 CascadingDropDowns to select a car model (sound familiar? ) . When the user selects the final drop-down, I want to create a set of check boxes based on the last drop-down's value. I am not using a FormView, just a simple form. The SelectedIndexChanged event is not firing straight away. I have another field in the form (vehicle registration date), on which the check box set also depends, so I have an OnTextChanged event set for this too. With me so far? Now, if I fill the drop-downs in a cascade using a modal window (all of which seems to work nicely), the SelectedIndexChanged event is not firing on the last drop-down. If, however, after this, I then change my text box value, the SelectedIndexChanged event for the drop-down chooses this moment to fire, followed by the OnTextChanged event for the text box. It's as if the event is getting held up or saved for later use. Is this all part of the same problem? Is there a work around I can use?
Here's my page code:
<span class="oneline" id="spDVLALookup" runat="server" visible="false"> <asp:Button ID="btnDVLALookup" Text="DVLA Lookup" runat="server" Visible="false" /></span><span class="oneline"> <span class="txtName">Manufacturer: </span><asp:DropDownList ID="ddManuf" runat="server" Width="300"> </asp:DropDownList></span><br /><span class="oneline"> <span class="txtName">Range: </span><asp:DropDownList ID="ddRange" runat="server" Width="300"></asp:DropDownList></span><br /><span class="oneline"> <span class="txtName">Model: </span><asp:DropDownList ID="ddModel" runat="server" Width="300"></asp:DropDownList></span><br /><span class="oneline"> <span class="txtName">Derivative: </span> <asp:DropDownList ID="ddDeriv" AutoPostBack="true" OnSelectedIndexChanged="ddDeriv_SelectedIndexChanged" runat="server" Width="300"> <asp:ListItem></asp:ListItem> </asp:DropDownList></span><br /><span class="oneline"> <span class="txtName">Date First Registered: </span> <asp:TextBox ID="tb1stRegDate" runat="server" Width="300" AutoPostBack="true" OnTextChanged="tb1stRegDate_TextChanged" /></span><br /><cc1:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="ddManuf" Category="Manuf" PromptText="-- Manufacturer --" LoadingText="[Loading manufacturers...]" ServicePath="~/Services/CAPData.asmx" ServiceMethod="GetData" /><cc1:CascadingDropDown ID="CascadingDropDown2" runat="server" TargetControlID="ddRange" Category="Range" PromptText="-- Range --" LoadingText="[Loading ranges...]" ServicePath="~/Services/CAPData.asmx" ServiceMethod="GetData" ParentControlID="ddManuf" /><cc1:CascadingDropDown ID="CascadingDropDown3" runat="server" TargetControlID="ddModel" Category="Model" PromptText="-- Model --" LoadingText="[Loading models...]" ServicePath="~/Services/CAPData.asmx" ServiceMethod="GetData" ParentControlID="ddRange" /><cc1:CascadingDropDown ID="CascadingDropDown4" runat="server" TargetControlID="ddDeriv" Category="Deriv" PromptText="-- Derivative --" LoadingText="[Loading derivatives...]" ServicePath="~/Services/CAPData.asmx" ServiceMethod="GetData" ParentControlID="ddModel" />
Here's the code to enable the button at the top:
// Add the DVLA lookup buttonif (myVt.VIN.Length > 0 || myVt.Registration.Length > 0){ spDVLALookup.Visible =true; btnDVLALookup.Visible =true; btnDVLALookup.OnClientClick ="this.value='Please Wait'; this.disabled=true; DVLALookup(this, '" + myVt.VIN +"', '" + myVt.Registration +"');";}Here's the JavaScript which does the modal window lookup (this JavaScript is not in the page Head because this page sits in a Master page):
function DVLALookup(button, vin, reg){ aryValues = new Array(); button.disabled = true; button.value = "Please Wait"; var url = "../../ExperianCapData/GetExperianData.aspx?vin=" + vin + "?istration=" + reg; if (navigator.appName != "Netscape") { lleft = (screen.availWidth/2) + 80; ttop = (screen.availHeight/2)-250; } strTemp = window.showModalDialog(url,aryValues,"dialogWidth:400px;dialogHeight:500px;dialogLeft:"+lleft+"px;dialogTop:"+ttop+"px;center:no;resizable:no;status:no;"); button.disabled = false; button.value = "DVLA Lookup"; if (strTemp.length > 0 && document.forms[0].ctl00_main_hfCapCode != null) { document.forms[0].ctl00_main_hfCapCode.value = strTemp; }}Actually, I've fixed this by putting the value from the modal window (as you might have guessed from the last line of my JavaScript) into a hidden field which fires a OnValueChanged event, which in turn populates the drop-downs with the correctly selected items. I then have a logic check in my SelectedValueChanged method for the final drop-down ("derivative"), which only creates my set of check boxes for the SelectedValueChanged event if the value of the bottom drop-down is different from the one in the hidden field. This allows users to select a derivative manually (i.e. not via the modal window lookup). Also, if the SelectedValueChanged event gets delayed and fired at the same time (well OK just before) the ValueChanged event for my registration date field, it will see that its value is the same as the hidden one, so it won't try to set off the creation of the check boxes.
It's a bit clumsy, but it works. Of course, in the future I might try to split this form into TabPanels or AccordionPanes - although there was a problem with the latter, which I've forgotten. Meanwhile, if anyone can see an obvious flaw in my logic or a better way to do this, or even solve why the drop-down SelectedValueChanged event is getting delayed by one postback, please feel free to comment
Cheers, Mundo
CascadingDropDown