Showing posts with label database. Show all posts
Showing posts with label database. Show all posts

Monday, March 26, 2012

Cascasding drop down - Error 500

Hi
I am playing with the cascading drop down control...
i have written a method to get data from sql 05 database and return andarray of CascadingDropDownNameValue. (i watched one of the how towebcasts on it)....anyway, i can get it to work else where but forsome reason its not working with this one.
I know the method is returning the right data as i have another methodwhich returns all values in a string[] i then dump on the screen andall is ok.
My CCD declaration.

<atlasT:CascadingDropDownID="CascadingDropDown1"runat="server">

<atlasT:CascadingDropDownProperties

Category="CategoryName"

ParentControlID="ddlClass"

TargetControlID="ddlCourses"

PromptText="All"ServiceMethod="GetCoursesByIdClass"

ServicePath="webservices/FillDropDowns.asmx"/>

</atlasT:CascadingDropDown>

My method...

[WebMethod]

publicCascadingDropDownNameValue[] GetCoursesByIdClass(string knownCategoryValues,string category)

{

// Get connection string from web.config

string dsn = System.Configuration.ConfigurationManager.ConnectionStrings["connCleo"].ConnectionString;

string[] categoryValues = knownCategoryValues.Split(':',';');

int idClass =Convert.ToInt32(categoryValues[1]);

// SQL script

string sql =@dotnet.itags.org."SELECT c.idCourse, c.chrName FROM cleo.Course c

JOIN cleo.CourseAssign ca ONca.idCourse=c.idCourse

WHERE idClass=@dotnet.itags.org.idClass

ORDER BY c.chrName";

// Generic list for collection

List<CascadingDropDownNameValue> cascadeCollection =newList<CascadingDropDownNameValue>();

// Open connection and execute command...loop through reader and add items to list.

using(SqlConnection conn =newSqlConnection(dsn))

using (SqlCommand cmd =newSqlCommand(sql, conn))

{

cmd.Parameters.AddWithValue("@dotnet.itags.org.idClass", idClass);

conn.Open();

using (SqlDataReader reader = cmd.ExecuteReader())

{

while (reader.Read())

{

cascadeCollection.Add(newCascadingDropDownNameValue(reader.GetString(1), reader[0].ToString()));

}

}

}

// return collection as an array.

return cascadeCollection.ToArray();

}


I dont know of anyway i can debugthis to see if i am infact getting the correct values back(not surewhat values i need to pass to the method to mimic the call from thetoolkit.)?

Hopefully someone can see where i am going wrong.??

Thanks
Steve

OK, so i am pulling my hair out and have no idea where to look for help other than here.

I have put the same code in another project and it works fine.

The only difference that i can see is the version of the Atlas and Toolkit dll.

The date stamp on the one that works is 04/05/2006
The one that doesnt work is 27/06/2006

So begs the question....what has changed in the June CTP that stops my service from working?

Any ideas?
Steve


Again...the brick wall.
I added in the new CTP dll's to my project that works and it still works.

If i add the old dll's into my not working project...i dont get error 500, but i do get a popup error when trying to change the selection of parent ddl...(eventvalidation error) and no, nothing is bound to the Drop down.

:-(

Steve


sorted it!!!!

I was missing stuff from the web.config file !!!

Well thats two hours of my life gone!!!

Steve


OK...new error now. i seem to be speaking to myself here but if anyone does join in maybe they can help.

The drop down is not binding fine...problem is when i try and postback (with button) i get a postback validation error (there are a few posts on here with no clear answer, none regarding the CDD control though)...anyway, so i turn of validation and the value in the second drop down list has nothing...it should be an number (as id for the text on display...nothing odd there).

I have tried

protectedoverridevoid Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(this.UniqueID);
base.Render(writer);
}

but this has no affect.

Steve


i was a touch hasty with my previous post...there is a value in the selectedvalue property....however i was checked that selectedindex > 0...even though it was, it wasnt (if that makes sense - the debugger says 0)...however i got round this withstring.IsNullOrEmpty(ddl.SelectedValue)

But now i have to have eventvalidation off.

What are the implications of this...surely this isnt correct? I must be able to have it turned on...not sure what i does but feel like i'm missing out!!!!!!

Anybody?

Steve


Seee http://forums.asp.net/thread/1293293.aspx #20

Event Validation just makes sure the values you posted from your dropdown are valid values you populated it with. But seeing as the cascading dropdown populates from script, this wont/cant work and if you need to, validate the values on the server (its a security thing)

Saturday, March 24, 2012

CascadingDropDownlist: How Do I Save the SelectedValue Back To Database

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.

CascadingDropDownList problem !

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

CascadingDropDownList and a MySQL database

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.

CascadingDropDown with database - newbie question

Sorry if this seems a bit obvious but I'm a relative newcomer to ASP.NET, especially Atlas, and am a bit stuck.

I have an Access database with three tables: tblRegions, tblProvinces and tblTowns. I want to use these tables to drive 3 related dropdown lists. It's no problem achieving this with server-side controls, but I want the performance advantages of client-side processing - hence my interest in Atlas.

I've followed the examples and, after a bit of a struggle, managed to get a "hard-coded" version working (with the names of Regions, Provnces, etc. embedded in the code), but now I'm ready to data-enable it.

I've looked for examples and can't find anything that covers everything I need to do. All the examples seem to assume a fairly high level of coding experience - especially in C# - whereas I'm more used to dragging and dropping datasources and coding, when strictly necessary, in VB. Can anyone explain the exact steps I need to follow to achieve what I want using VB and, preferably, using an Access data source?

At the moment, my code is as follows:
---------- Default.aspx --------------
<%@dotnet.itags.org. Page Language="VB" EnableEventValidation="false" %>
<%@dotnet.itags.org. Register
Assembly="AtlasControlToolkit"
Namespace="AtlasControlToolkit"
TagPrefix="atlasToolkit" %>
<!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 id="Head1" runat="server"><title>Test Page</title></head>
<body><form id="Form1" runat="server"><div>
<atlas:ScriptManager ID="ScriptManager1" runat="server" />
<table>
<tr>
<td align="right">Region: </td>
<td><asp:DropDownList ID="ddlRegion" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td align="right">Province: </td>
<td><asp:DropDownList ID="ddlProvince" runat="server"></asp:DropDownList></td>
</tr>
<tr>
<td align="right">Town: </td>
<td><asp:DropDownList ID="ddlTown" runat="server"></asp:DropDownList></td>
</tr>
</table>
<atlasToolkit:CascadingDropDown ID="cdd" runat="server">
<atlasToolkit:CascadingDropDownProperties
TargetControlID="DropDownList1"
Category="Region"
ServicePath="ListcountService.asmx"
ServiceMethod="GetRegions"
PromptText="-- Any Region --" />
<atlasToolkit:CascadingDropDownProperties
TargetControlID="ddlRegion"
Category="Region"
ServicePath="ListcountService.asmx"
ServiceMethod="GetRegions"
PromptText="-- Any Region --" />
<atlasToolkit:CascadingDropDownProperties
TargetControlID="ddlProvince"
ParentControlID="ddlRegion"
Category="Province"
ServicePath="ListcountService.asmx"
ServiceMethod="GetProvincesForRegion"
PromptText="-- Any Province --" />
<atlasToolkit:CascadingDropDownProperties
TargetControlID="ddlTown"
ParentControlID="ddlProvince"
Category="Town"
ServicePath="ListcountService.asmx"
ServiceMethod="GetTownsForProvince"
PromptText="-- Any Town --" />
</atlasToolkit:CascadingDropDown>
</div></form></body>
</html
----------- ListcountService.asmx ----------
<%@dotnet.itags.org. WebService Language="VB" Class="ListCountService1" %
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports AtlasControlToolkit

<WebService(Namespace := "http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class ListCountService1
Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function GetRegions(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Return New CascadingDropDownNameValue() _
{New CascadingDropDownNameValue("Lazio", 1), _
New CascadingDropDownNameValue("Tuscanny", 2), _
New CascadingDropDownNameValue("Umbria", 3)}
End Function

<WebMethod()> _
Public Function GetProvincesForRegion(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim kv As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim RegionId As Integer
If (kv.ContainsKey("Region") And Int32.TryParse(kv("Region"), RegionId)) Then
If (RegionId = 1) Then
Return New CascadingDropDownNameValue() _
{New CascadingDropDownNameValue("Upper Lazio", 11), _
New CascadingDropDownNameValue("Middle Lazio", 12), _
New CascadingDropDownNameValue("Lower Lazio", 13)}
ElseIf (RegionId = 2) Then
Return New CascadingDropDownNameValue() _
{New CascadingDropDownNameValue("Upper Tuscanny", 21), _
New CascadingDropDownNameValue("Middle Tuscanny", 22), _
New CascadingDropDownNameValue("Lower Tuscanny", 23)}
End If
End If
Return New CascadingDropDownNameValue() {}
End Function

<WebMethod()> _
Public Function GetTownsForProvince(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim kv As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim ProvinceId As Integer
If (kv.ContainsKey("Province") And Int32.TryParse(kv("Province"), ProvinceId)) Then
If (ProvinceId = 11) Then
Return New CascadingDropDownNameValue() _
{New CascadingDropDownNameValue("Upper Lazio Town 1", 111), _
New CascadingDropDownNameValue("Upper Lazio Town 2", 112), _
New CascadingDropDownNameValue("Upper Lazio Town 3", 113)}
ElseIf (ProvinceId = 12) Then
Return New CascadingDropDownNameValue() _
{New CascadingDropDownNameValue("Middle Lazio Town 1", 121), _
New CascadingDropDownNameValue("Middle Lazio Town 2", 122), _
New CascadingDropDownNameValue("Middle Lazio Town 3", 123)}
End If
End If
Return New CascadingDropDownNameValue() {}
End Function
End Class
---------------------------

Thanks in advace for your help,
AndrewHave you already followed theUsing CascadingDropDown with a Database walkthrough that comes with the Toolkit?
Yes, but I don't understand the GetColorsForModel function, especially the code that reads:

CarsTableAdapters.ColorTableAdapter adapter =
newCarsTableAdapters.ColorTableAdapter();

Cars.ColorDataTable colorTable =
adapter.GetColorsForModel(modelId);

List<CascadingDropDownNameValue> values =
new List<CascadingDropDownNameValue>();

foreach (DataRow drin colorTable)
{
values.Add(newCascadingDropDownNameValue(
(string) dr["Color"],
dr["ColorID"].ToString()));

Maybe I'm naive, but when I used plain ASP.NET (with VWD 2005), I found it very easy to set up a dropdown list. I just dragged a datasource object from the toolbox, set it up by defining a few properties and then dragged a dropdown list next to it and linked it to the datasource by defining more properties. No coding necessary. Coming from that experince, I guess I'm a bit daunted by the amount of C# that comes up in the examples. I'm prepared to get my hands dirty if necessary, but I was hoping that the toolkit would hold my hand a bit. Any ideas?

The CascadingDropDown is more complex because it enables a richer scenario. The web service it calls has the ability to return any set of data based on any information. In the sample above, it's querying part of a database to return only the subset of data that's needed by the CDD that's about to populate. I believe that if you walk through the code above with the MSDN documentation, the purpose of each line should not be too difficult to understand. Once you understand how this example is working, if you have any suggestions for simplifying it from the point of view of someone who's just gone through the process, we'd certainly love to hear them!!

Thanks for your help!


Thanks for my help? I thought it was you helping me!

Anyway, it looks like I can't connect to the database table by dragging and dropping a DataSource object from the toolbox like- right? I need to make the connection in code. As a newbie used to ASP.NET and VWD2005, that's a bit daunting - especially since the example is in C# and I'm more used to VB.

Could you please point me to a code example (preferably in VB) that shows how to connect to an Access database table and put the results into an array?

Thanks in advance
OK here's an update. After much scrabbling around the MSDN documentation, and a lot of trial-and-error guesswork, I've finally managed to make some progress. This is the updated version of my GetRegions function:

Public Function GetRegions(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim objAdapter As New System.Data.OleDb.OleDbDataAdapter _
("SELECT regID, regName FROM tlkpRegionList ORDER BY RegID", _
"Provider = Microsoft.Jet.OLEDB.4.0;" & _
"User ID = Admin;" & _
"Data Source=D:\WebSites\AtlasWebSite\App_Data\TiberPass.mdb")
Dim objDataSet As New System.Data.DataSet()
objAdapter.Fill(objDataSet)
Dim objTable As System.Data.DataTable
objTable = objDataSet.Tables(0)
With objTable
Dim intRow As Integer
For intRow = 0 To .Rows.Count - 1
Return New CascadingDropDownNameValue() _
{New CascadingDropDownNameValue(.Rows(intRow).ItemArray(1), .Rows(intRow).ItemArray(0))}
Next intRow
End With
Return New CascadingDropDownNameValue() {}
End Function

It succesfully gets a record from my database table. However, there are several problems:

1) I used the absolute path to connect to the Access database file. This won't port onto a web-server. Is there a way to use a relative path instead?

2) At this stage, I've only managed to retrieve one record. I want to loop through all the records in the table, but I don't know how to add additional entries to the CDD. Any clues?

3) Assuming I can solve the above problems, there's still a flaw when it comes to the other two CDDs. They are going to need logic (IF statements, etc.) so that they are populated with data depending on the user selection in the "upstream" CDDs. It seems that I'll need to make calls to the database (on the server) to achieve this. I feel it would be better if I could somehow make a single call to the database to get the contents of the three tables (into a DataSet?) for client-side processing. That would avoid repeated calls back to the server. Any idea how to achieve this?

Thanks again for your help,
Andrew

1: You can probably use relative paths. Someone who knows Access access can probably help here.

2: You want to build an array of CascadingDropDownNameValue objects, then return the array. Your code's set up for looping through the returned rows, but always returns just the first CascadingDropDownNameValue it creates.

3: Each CDD populates independently, so each associated web method should query the database to get the data it needs. That said, each call can use the information available to it about the values of the parent control(s) to filter that data. But there will be one web service call for each CDD when it needs to populate. If you want to cache things in your web methods such that you only ever need to make one database call, that's certainly something you can do.


I've solved point 1 (relative path) by replacing my code:
"Data Source=D:\WebSites\AtlasWebSite\App_Data\TiberPass.mdb")
with:
"Data Source=" & Server.MapPath(".") & "\App_Data\TiberPass.mdb")
I've yet to test this on a web server, but it works on my local machine.

Point 2 (returning an array of CascadingDropDownNameValue objects) is a bit more daunting.

Point 3 (caching table data) is something I can look into later. So...

Any advice on how to set up and return an array of CDD NameValue objects?

Hi Android,

The key bits you need are as follows:

Dim

valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)

For intRow = 0 To .Rows.Count - 1

values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(1).ToString, .Rows(intRow).ItemArray(0)))

Next

Return

values.ToArray

Not sure I've copy and pasted your data in exactly right, but essentially when you add the CascadingDropDownNameValue pair, you need to put in the displayed text as a string then the hidden value (which doesn't have to be a string - and is obviously normally an Integer type ID field from your db).

Any probs, drop a reply.

Simon


Should've checked the preview, damn editor moved things onto next lines....... here's another try.

The key bits you need are as follows:

Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)

For intRow = 0 To .Rows.Count - 1

values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(1).ToString, .Rows(intRow).ItemArray(0)))

Next

Return values.ToArray

Simon


Thanks a lot Simon, that's exactly the help I needed.Big Smile After adding the lineImports System.Collections.GenericI now have the whole thing working. Thanks again.

I'm now interested in making it more efficient (addressing point (3)). At the moment, every time the user selects a dropdown value, the "downstream" dropdown(s) must be re-populated by a call to the appropriate webservice functions. That's fine but these functions make calls to the database. It seems to me that, since this is fairly static data (new towns don't appear every day) it would be better to make one call at the start and cache the results for later use. That would reduce the number of calls to the database and, presumably, improve performance.

I read in the MSDN documentation that the Data Adapter object (OleDbDataAdapter) can hold a "local" copy of a set of tables. Maybe I could populate this once and then fill my data sets from it when I need to. Trouble is, I'm not sure how to do this - including where to put the code so it's kept available to my functions. I guess I'm thinking of it a bit like a good 'ol global variable - but I guess that's not very object-oriented. Perhaps I need to create a class with Set and Get methods?

I've also notice that a lot of my logic is duplicated between the three webservice functions, e.g. setting up the connection to the database. That makes me think that it may be better to create a single parameterized function (or maybe the class mentioned above), that each function calls with a table name and which returns the CDD array to the calling function. I know the concepts, but my coding skills aren't really up to it.

Finally, I'm concerned about housekeeping, i.e. tidying up and closing objects that are no longer needed to free up resources.

It seems to me that, with a lot of help, I've managed to solve the main problems in getting this working. Maybe someone out there would be interested in addressing the issues I've mentioned above and creating an efficient and flexible object that accepts parameters, such as table names, and returns the appropriate arrays to populate the CDDs whilst hiding all the complexity from the developer. Come to think of it, it would be really great if such an object were part of the Atlas Control Toolkit. That way, novice developers could drag and drop it onto the work surface from the toolbox and set a few properties to get it working. That's my feedback to Microsoft. I like using ASP.NET and Visual Web Developer because I can achieve most of the common tasks without needing to write any code. Having created a set of CDDs in standard ASP.NET, I was dissappointed by the performance. So I had a look at Atlas - but I was suddenly thrown from the cosy drag-and-drop world I was used to into a world of C# code. I would have thought that this was a common enough requirement among web developers to be worth addressing.

Anyway, for anyone interested, my complete webservice code now reads:

<%@.WebServiceLanguage="VB"Class="ListCountService" %>

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports AtlasControlToolkit

Imports System.Collections.Generic

<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

PublicClass ListCountService

Inherits System.Web.Services.WebService

<WebMethod()> _

PublicFunction GetRegions(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()

Dim objAdapterAsNew System.Data.OleDb.OleDbDataAdapter _

("SELECT regID, regName FROM tlkpRegionList ORDER BY regID", _

"Provider = Microsoft.Jet.OLEDB.4.0;" & _

"User ID = Admin;" & _

"Data Source=" & Server.MapPath(".") &"\App_Data\TiberPass.mdb")

Dim objDataSetAsNew System.Data.DataSet()

objAdapter.Fill(objDataSet)

Dim objTableAs System.Data.DataTable

objTable = objDataSet.Tables(0)

With objTable

Dim intRowAsInteger

Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)

For intRow = 0To .Rows.Count - 1

values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(1).ToString, .Rows(intRow).ItemArray(0)))

Next

Return values.ToArray

EndWith

ReturnNew CascadingDropDownNameValue() {}

EndFunction

<WebMethod()> _

PublicFunction GetProvincesForRegion(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()

Dim kvAs StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)

Dim RegionIdAsInteger

If (kv.ContainsKey("Region")And Int32.TryParse(kv("Region"), RegionId))Then

Dim objAdapterAsNew System.Data.OleDb.OleDbDataAdapter _

("SELECT provID, provName FROM tlkpProvinceList WHERE provRegion=" & RegionId &" ORDER BY provID", _

"Provider = Microsoft.Jet.OLEDB.4.0;" & _

"User ID = Admin;" & _

"Data Source=" & Server.MapPath(".") &"\App_Data\TiberPass.mdb")

Dim objDataSetAsNew System.Data.DataSet()

objAdapter.Fill(objDataSet)

Dim objTableAs System.Data.DataTable

objTable = objDataSet.Tables(0)

With objTable

Dim intRowAsInteger

Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)

For intRow = 0To .Rows.Count - 1

values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(1).ToString, .Rows(intRow).ItemArray(0)))

Next

Return values.ToArray

EndWith

EndIf

ReturnNew CascadingDropDownNameValue() {}

EndFunction

<WebMethod()> _

PublicFunction GetTownsForProvince(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()

Dim kvAs StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)

Dim ProvinceIdAsInteger

If (kv.ContainsKey("Province")And Int32.TryParse(kv("Province"), ProvinceId))Then

Dim objAdapterAsNew System.Data.OleDb.OleDbDataAdapter _

("SELECT townID, townName FROM tlkpTownList WHERE townProvince=" & ProvinceId &" ORDER BY townID", _

"Provider = Microsoft.Jet.OLEDB.4.0;" & _

"User ID = Admin;" & _

"Data Source=" & Server.MapPath(".") &"\App_Data\TiberPass.mdb")

Dim objDataSetAsNew System.Data.DataSet()

objAdapter.Fill(objDataSet)

Dim objTableAs System.Data.DataTable

objTable = objDataSet.Tables(0)

With objTable

Dim intRowAsInteger

Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)

For intRow = 0To .Rows.Count - 1

values.Add(New CascadingDropDownNameValue(.Rows(intRow).ItemArray(1).ToString, .Rows(intRow).ItemArray(0)))

Next

Return values.ToArray

EndWith

EndIf

ReturnNew CascadingDropDownNameValue() {}

EndFunction

EndClass


I have now stumbled my way through creating my own first cascading dropdown (hooked into a database, and all in VB), and it is thanks largely to the posts here. I'm so happy I got it to work! For the sake of others trying to do this same thing, I will also post my code here, so that others may benefit. Also, if any experts out there see something inefficient in the code below, please let me know - I want this project to be as successful as possible! Thanks! - Matthew

In the aspx file that contains the dropdownlist:

<%

@.Register
Assembly="AtlasControlToolkit"Namespace="AtlasControlToolkit"TagPrefix="cc1" %>

That's at the top. Now, down in the area where we are using the drop down lists:

<cc1:CascadingDropDownID="CascadingDropDown1"runat="server">
<cc1:CascadingDropDownProperties
TargetControlID="DropDownList4"PromptText="Please select a product group name."ServicePath="ProductsService.asmx"ServiceMethod="GetProductGroups"Category="Group"/><cc1:CascadingDropDownProperties
TargetControlID="DropDownList5"PromptText="Please select a product code."ParentControlID="DropDownList4"ServicePath="ProductsService.asmx"ServiceMethod="GetCatalogCodesForGroup"Category="CatalogCode"/><cc1:CascadingDropDownProperties
TargetControlID="DropDownList6"PromptText="Please select a product description."ParentControlID="DropDownList5"ServicePath="ProductsService.asmx"ServiceMethod="GetProductsForCatalogCode"Category="Product"/>

</cc1:CascadingDropDown>

Now, I created theProductsService.asmxfile and put the follwing code in the .vb codebehind file:

Imports

System.Web

Imports

System.Web.Services

Imports

System.Web.Services.Protocols

Imports

System.Xml

Imports

System.Collections.Generic

Imports

AtlasControlToolkit

Imports

System.Data.SqlClient

<WebService(Namespace:=

"http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<

Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

Public

Class ProductsServiceInherits System.Web.Services.WebService

<WebMethod()> _

PublicFunction GetProductGroups(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()
'-- Declare the "List" of Name/Value pairs that we will build with our query to the databaseDim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)Dim conAs SqlConnectionDim SQLcmdAs SqlCommandDim DataRAs SqlDataReaderDim strSQLAsString'-- Select all of the GroupNames from the database

strSQL =

"SELECT DISTINCT([GroupName]) FROM dbo_C_CatalogGroup ORDER BY GroupName"

con =

New SqlConnection(ConfigurationManager.ConnectionStrings.Item("CrosbyCertSQLConnectionString").ConnectionString)

con.Open()

SQLcmd =

New SqlCommand(strSQL, con)

DataR = SQLcmd.ExecuteReader()

While DataR.Read()

values.Add(

New CascadingDropDownNameValue(DataR("GroupName"), DataR("GroupName")))EndWhile

DataR.Close()

con.Close()

Return values.ToArray()EndFunction

<WebMethod()> _

Public

Function GetCatalogCodesForGroup(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()
Dim kvAs StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)If (kv.ContainsKey("Group"))Then
'-- Declare the "List" of Name/Value pairs that we will build with our query to the databaseDim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)Dim conAs SqlConnectionDim SQLcmdAs SqlCommandDim DataRAs SqlDataReaderDim strSQLAsString'-- Select all of the CatalogCodes from the database

strSQL =

"SELECT [CatalogCode] FROM dbo_C_CatalogGroup WHERE [GroupName] = '" & kv("Group") &"' ORDER BY [CatalogCode]"

con =

New SqlConnection(ConfigurationManager.ConnectionStrings.Item("CrosbyCertSQLConnectionString").ConnectionString)

con.Open()

SQLcmd =

New SqlCommand(strSQL, con)

DataR = SQLcmd.ExecuteReader()

While DataR.Read()

values.Add(

New CascadingDropDownNameValue(DataR("CatalogCode"), DataR("CatalogCode")))EndWhile

DataR.Close()

con.Close()

Return values.ToArray()ExitFunctionEndIf'-- Return an empty list, otherwiseReturnNew CascadingDropDownNameValue() {}EndFunction

<WebMethod()> _

Public

Function GetProductsForCatalogCode(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()
Dim kvAs StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)If (kv.ContainsKey("CatalogCode"))Then
'-- Declare the "List" of Name/Value pairs that we will build with our query to the databaseDim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)Dim conAs SqlConnectionDim SQLcmdAs SqlCommandDim DataRAs SqlDataReaderDim strSQLAsString'-- Select all of the Product Descriptions from the database

strSQL =

"SELECT [Description], [ProductCode] FROM dbo_C_Product WHERE [CatalogCode] = '" & kv("CatalogCode") &"' ORDER BY [ProductCode]"

con =

New SqlConnection(ConfigurationManager.ConnectionStrings.Item("CrosbyCertSQLConnectionString").ConnectionString)

con.Open()

SQLcmd =

New SqlCommand(strSQL, con)

DataR = SQLcmd.ExecuteReader()

While DataR.Read()

values.Add(

New CascadingDropDownNameValue(DataR("Description"), DataR("ProductCode")))EndWhile

DataR.Close()

con.Close()

Return values.ToArray()ExitFunctionEndIf'-- Return an empty list, otherwiseReturnNew CascadingDropDownNameValue() {}EndFunction

End

Class

Thank you very much for your example! It helped me out tramendously. I did have to modify your example some as I was using a SQL DataSet and TableAdapters. My tread is at:

http://forums.asp.net/thread/1362449.aspx

Cascadingdropdown with database

I was reading about cascadingdropdown and i see an example to work with a database with webservice but my application architecture don`t permit do that. i have to call another class first. well there an example of cascadingdropdown to call a metod on the page in place webservice?

regardsThe CascadingDropDown sample page that comes with the Toolkit shows how to use it with both a web service and a page method.

CascadingDropDown with a Database, Method Error 405

Hey guys,


I followed the AjaxControlToolki tinstructions on how to create a WebService and specify everything so that it would populate two DropDownLists. The problem is, the first DropDownList has a [Method Error 405] as its only value. If I select it, the second DropDownList is populated with the same.

After checking, rechecking and extensively searching, I haven't found my error. I've read at least a dozen topics on this error but none have helped me.

Here is my code:

App_Code/StateServices.cs:

using System;
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;

/// <summary>
/// Summary description for StateServices
/// </summary>[WebService(Namespace ="http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.Web.Script.Services.ScriptService]public class StateServices : System.Web.Services.WebService { GeographicalDelimitationsDB GeoDataSource = new GeographicalDelimitationsDB(); GeographicalDelimitationsDBTableAdapters.CountyInfoTableAdapter GeoCountyInfoTableAdapter = new GeographicalDelimitationsDBTableAdapters.CountyInfoTableAdapter(); GeographicalDelimitationsDBTableAdapters.ZipCodesTableAdapter GeoZipCodesTableAdapter = new GeographicalDelimitationsDBTableAdapters.ZipCodesTableAdapter(); public StateServices() { } [WebMethod] public CascadingDropDownNameValue[] GetCounties(string knownCategoryValues, string category) { GeographicalDelimitationsDB.CountyInfoDataTable counties = GeoCountyInfoTableAdapter.GetData(); List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>(); foreach (DataRow dr in counties.Rows) { string name = (string)dr["Name"];
int countyID = (int)dr["CountyCode"];

values.Add(new CascadingDropDownNameValue(name, countyID.ToString()));
}

return values.ToArray();
}

[WebMethod]
public CascadingDropDownNameValue[] GetCitiesForCounty(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

int countyID;

if (!kv.ContainsKey("County") || !Int32.TryParse(kv["County"], out countyID))
{
return null;
}

GeographicalDelimitationsDB.ZipCodesDataTable cities = GeoZipCodesTableAdapter.GetDataByCountyID(countyID);

List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();

foreach (DataRow dr in cities.Rows)
{
values.Add(new CascadingDropDownNameValue((string)dr["City"], dr["ZIP"].ToString()));
}

return values.ToArray();
}
}

 
index.aspx: 

 <asp:UpdatePanel ID="NavigationUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Panel ID="ConfigurationContentPart" runat="server" CssClass="module-content">
<h3>County:</h3>
<p>
<asp:DropDownList ID="CountyList" runat="server" onchange="selectCounty(this)" />
</p>
<h3>City:</h3>
<p>
<asp:DropDownList ID="CityList" runat="server" onchange="selectCity(this)" />
</p>
</asp:Panel
<ajaxToolkit:CascadingDropDown ID="CountyCascadingDropDown" runat="server" TargetControlID="CountyList" Category="County" PromptText="Select a County" LoadingText="[Loading...]" ServicePath="StateServices.asmx" ServiceMethod="GetCounties" />
<ajaxToolkit:CascadingDropDown ID="CityCascadingDropDown" runat="server" TargetControlID="CityList" Category="City" PromptText="Select a City" LoadingText="[Loading...]" ServicePath="StateServices.asmx" ServiceMethod="GetCitiesForCounty" ParentControlID="CountyList" /
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>

Bump...

Please help, I'm really stuck!


Does it work without the onchange handlers on the DropDownLists?

CascadingDropDown with a Database fails when Table has more than 908 rows

Using CascadingDropDown with a Database fails when Table has more than 908 rows

with "SELECT * FROM TABLA1" CascadingDropDown fails with message [Method error 500] otherwise with "SELECT TOP 908 * FROM TABLA1" works fine.

can somebody help me? my Table has more than 908 rows, I need to load about 1100 rows

Thanks

It's due to this:http://ajax.asp.net/docs/mref/P_System_Web_Script_Serialization_JavaScriptSerializer_MaxJsonLength.aspx

The JSON serializer has a default max length (see the bottom of the entry). Increase that number in web.config.


thank you for your quick and accurate responseBig Smile now it works

have been a pleasure


hi,

i have tried to uncomment the <jsonserialization> attribute in the web.config file. i get an error at method error[12030]. i need to retrive about 2000 rows in my dropdown list. any help would be greatly appreciated.


ooops..its working now.i had previously included teh convert tag below the json tag in the web.config file. when i removed the converter tag, its working well...

CascadingDropDown with a database

I have read several similar post but yet no solution

Hello I am tryingto use Ajax CascadingDropDown with a database.

My database structure is:

IssueID(PK)
GroupID
ParentIssueID
IssueName


There are 3 dropdown list.
The first dropdown list retrieves data from the datble with parent ID = -1.
While the second drop down list retrieves it info based on the selected value (ID) of the first dropdownlist.

say we have in the table:

IssueID GroupID ParentIssueID IssueName
1 1 -1 Housing
2 1 1 Electronics
3 2 -1 Garden
4 1 2 Microwave

So, in the case the first dropdown retrives all data from the table with (ParentIssueID= -1) so here we have: Housing and Garden. both IssueIS and IssueName are returned.

Onselecting (say housing), the second dropdown retrieves any row with -> ParentIssueID = IssueID(value of ddl) of the selected value is the first dropdown. Here we have Electronics retured.

The third dropdown returns the list of rows based of the value of the selected ddl. Here we have Microwave.
Thus we have:
First ddl: Housing
Second ddl: Electronics
Third ddl: Microwave


Below is my web method:

<WebMethod()> _
Public Function GetMainIssue(ByVal knownCategoryValues As Integer, ByVal category As String) As CascadingDropDownNameValue()
Dim maindepth As Integer = 1

Dim mainIssueAdapter As New mainIsseDataTableAdapters.GetDepthTableAdapter()
Dim mainIssue As mainIsseData.GetDepthDataTable = mainIssueAdapter.GetMainIssue(maindepth)
Dim values As New List(Of CascadingDropDownNameValue)()

For Each dr As DataRow In mainIssue
Dim IssueName As String = DirectCast(dr("IssueName"), String)
Dim IssueID As Integer = CInt(dr("IssueID"))
values.Add(New CascadingDropDownNameValue(IssueName, IssueID))
Next

Return values.ToArray()

End Function


<WebMethod()> _
Public Function GetSubIssue(ByVal knownCategoryValues As Integer, ByVal category As String) As CascadingDropDownNameValue()

Dim kv As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim IssueID As Integer

If Not kv.ContainsKey("mainIssue") OrElse Not Int32.TryParse(kv("mainIssue"), IssueID) Then
Return Nothing
End If

Dim subIssuesAdapter As New subIssueDataTableAdapters.GetAllCategoryTableAdapter()
Dim subIssue As subIssueData.GetAllCategoryDataTable = subIssuesAdapter.GetSubIssue(IssueID)

Dim values As New List(Of CascadingDropDownNameValue)()

For Each dr As DataRow In subIssue
values.Add(New CascadingDropDownNameValue(DirectCast(dr("IssueName"), String), dr("IssueID").ToString()))
Next

Return values.ToArray()

End Function


In my aspx file I have
<asp:DropDownList id="drpMainCategory" runat="server">

<cc1:cascadingdropdown id="CascadingDropDown2" runat="server" loadingtext="[Loading...]"
prompttext="Please select a Main Issue" servicepath="../UpdateDropDown.asmx"
targetcontrolid="drpMainCategory" Category="getmain" ServiceMethod="GetMainIssue"></cc1:cascadingdropdown>

I get an error(500 or 12030) when I run it.
Also, I cant figure out what exactly the category field is for <cc1:cascadingdropdown control. how do I optain it. Any comments or similar code to help would be greatly appreciated.
Thanks

Please refer to this thread: http://forums.asp.net/t/1122659.aspx

CascadingDropDown send to database

Hello, hi have 3 cascadingdropdown..

Every thibk works fine but when i click in the button to save the form( or another postback) i cant pick the selected values..

For data returned form the database i do:

AtlasControlToolkit.CascadingDropDownProperties propDist = cascDrpDist.GetTargetProperties(DropDownDist);

propDist.SelectedValue = dt.Rows[0].Table.Rows[0].ItemArray[15].ToString();

AtlasControlToolkit.CascadingDropDownProperties propConc = cascDrpDist.GetTargetProperties(DropDownConc);

propConc.SelectedValue = dt.Rows[0].Table.Rows[0].ItemArray[14].ToString();

AtlasControlToolkit.CascadingDropDownProperties propFreg = cascDrpDist.GetTargetProperties(DropDownFreg);

propFreg.SelectedValue = dt.Rows[0].Table.Rows[0].ItemArray[13].ToString();

to save values for the postbacks

hfCDISTRITO.Text = cascDrpDist.TargetProperties[0].SelectedValue;

hfCCONCELHO.Text = cascDrpDist.TargetProperties[1].SelectedValue;

hfCFREGUESIA.Text = cascDrpDist.TargetProperties[2].SelectedValue;

but if im inserting a new data how can i do so pick the selectedvalues?

Thanks

MArcos ALves

but if im inserting a new data how can i do so pick the selectedvalues?

sorry i want to say:

but if im inserting a new data how can i pick the selectedvalues?

Please help!! im trying this about 3 weeks!!!!Tongue Tied[:'(]

Thanks a lot!


I'm afraid I don't understand the scenario. Could you please describe it a little more?

Wednesday, March 21, 2012

CascadingDropDown options not showing.

I have 2 dropdown boxes with the CascadingDropDown ajax extension attached to them, they are reading from an xml file not database. I dont get an error but my first dropdown bar shows "Please select an option" ie my prompt text, but not the xml options... my xml is set out correctly (ie the same hierarchical XML layout as the sample ajax website). Any ideas why this isnt showing me options but doesnt error? thanks in advance John

i feel as though i should explain more. Basically ive got an xml file layed out like :

<?xml version="1.0" encoding="utf-8" ?>
<GroupService>
<Group name="One">
<SubGroup name="One" />
<SubGroup name="Two" />
</Group>
</Service>

Based on two categorys. I have two drop down boxes with the code :

<asp:DropDownList ID="DropDownList1" runat="server">
</asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Group" PromptText="Please select a Type" LoadingText="[Loading makes...]"
ServicePath="GroupsService.asmx" ServiceMethod="GetDropDownContents" /
<asp:DropDownList ID="DropDownList2" runat="server">
</asp:DropDownList>
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown2" runat="server" TargetControlID="DropDownList2"
Category="SubGroup" PromptText="Please select a Group Type" LoadingText="[Loading models...]"
ServiceMethod="GroupsService.asmx" ParentControlID="DropDownList1" /
The ServiceMethod is correctly referance.Now my webservice is :

using System;
using System.Web;
using System.Collections;
using System.Collections.Specialized;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml;

/// <summary>
/// Summary description for GroupsService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class GroupsService : System.Web.Services.WebService
{
// Member variables
private static XmlDocument _document;
private static object _lock = new object();

// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/GroupsService.xml"));
}
}
return _document;
}
}

public static string[] Hierarchy
{
get { return new string[] {"Group", "SubGroup" }; }
}

public GroupsService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);

// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category);
}

}

It doesnt give me an error and it says its loading but then no items are shown, has anyone else had this error? thanks in advance John


did a little bit of work on this and saw in the sample website i got with the ajax download the hierarchy is :

public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}

it misses out the last value ie color of the colours. so i change mine to :

public static string[] Hierarchy
{
get { return new string[] { "Group" }; }
}

ie got rid of the last valuein the hierarchy, but still no luck, does anyone know if it is possible to do this from 2 dropdown boxes rather than 3? if so can someone point me in the right direction? thanks in advance John


Hi,

Please refer to thisthread for how to use a XML document with different format.

Or you can change attribute "name" to "value" .


I have had the same issue all day.. Finally noticing the only difference between mine and the sample was case, I tried making the xml attribute strings names lower case ie.. <group> <subgroup> and made sure the heirarchy property was also lower case and they now populate.

Hope this helps

CascadingDropDown not populating

Hi

I'm trying to use the CascadingDropDown with a database in VB, using page methods.

My three DropDownLists are drpProject, drpFixFor and drpFixForSub. The drpProject control is populated fine when the page loads; and I'd expect the drpFixFor control to be populated when drpProject is changed, however, this is not happening.

The drpFixFor control is being enabled, but not populated - my "GetFixForList" function doesn't appear to be calledat all. (I put a breakpoint in it, and the breakpoint isn't hit.)

Interestingly, if I remove ParentControlID="drpProject" from drpFixFor's extender, the function is called as expected when the page loads.

My aspx page is:

<%

@dotnet.itags.org.PageLanguage="VB"MasterPageFile="~/MasterPage.master"AutoEventWireup="false"CodeFile="Test.aspx.vb"Inherits="Test"Title="" %>

<%

@dotnet.itags.org.RegisterAssembly="AtlasControlToolkit"Namespace="AtlasControlToolkit"TagPrefix="atlasToolkit" %>

<

asp:ContentID="Content1"ContentPlaceHolderID="cphBody"runat="Server">
<table> <tr> <tdstyle="width: 100px">Project:</td> <td><asp:DropDownListID="drpProject"runat="server"/></td> </tr> <tr> <tdstyle="width: 100px">Fix For:</td> <td><asp:DropDownListID="drpFixFor"runat="server"/></td> </tr> <tr> <tdstyle="width: 100px">Fix For Sub:</td> <td><asp:DropDownListID="drpFixForSub"runat="server"/></td> </tr></table><atlasToolkit:CascadingDropDownID="CascadingDropDown1"runat="server"> <atlasToolkit:CascadingDropDownPropertiesTargetControlID="drpProject"Category="Project"PromptText="(Select One)" ServiceMethod="GetProjectList"/> <atlasToolkit:CascadingDropDownPropertiesTargetControlID="drpFixFor"Category="FixFor"PromptText="(Select One)"ParentControlID="drpProject"ServiceMethod="GetFixForList"/> <atlasToolkit:CascadingDropDownPropertiesTargetControlID="drpFixForSub"Category="FixForSub"PromptText="(Select One)"ParentControlID="drpFixFor"ServiceMethod="GetFixForSubList"/></atlasToolkit:CascadingDropDown>

</

asp:Content>

And my Code Behind page is:

Imports

AtlasControlToolkit

Imports

System.Web.Services

Partial

Class Test Inherits System.Web.UI.Page

<WebMethod()> _

PublicFunction GetProjectList(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue() Dim valuesAsNew Generic.List(Of CascadingDropDownNameValue) ForEach myProjectAs ProjectIn Project.GetList

values.Add(

New CascadingDropDownNameValue(myProject.Name, myProject.ID)) Next Return values.ToArray EndFunction

<WebMethod()> _

PublicFunction GetFixForList(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue() Dim valuesAsNew Generic.List(Of CascadingDropDownNameValue) ' Hardcode to Project "2" for debugging ForEach myFixForAs FixForIn FixFor.GetList(2)

values.Add(

New CascadingDropDownNameValue(myFixFor.Name, myFixFor.ID)) Next Return values.ToArray EndFunction

End

Class

Note: "Project" and "FixFor" are objects defined in my App_Code folder, and their "GetList" functions return data from the SQL database.

Any ideas?

Thanks,
Andrew

I am also facing some issues with the cascadingdropdown extender, my question is that what if my database schema is such that i dont have ID for the fields in the drop downs, cant i fetch the value in the second drop down with the string value in the first drop down. As i understand this, ID seems to be added mandatorily in this extender.

-Pratibha


I don't see anything wrong with your code - what happens if you change all three service method's to call the one that's workng? Does it get called then?

Pratibha - I don't understand your question. ID isn't added by the extender at all - you can put whatever you want into the value field of the CascadingDropDownNameValue.


hey shawn, now i get it..hadnt looked carefully through the tool kit code earlier. It makes sense now and the cascadingdropdown works perfectly :)
Cool!

Hi

I've tried setting all three service methods to call GetProjectList, and still no luck - the function's called once when the page is loaded to populate the first DropDown, and not called for the others.

Thanks,
Andrew


To fix this, you need to add EnableEventValidation="false" to your Page directive. This should be a FAQ for CascadingDropDown, but basically ASP.NET tries to make sure that postbacks don't contain stuff they shouldn't based on what it knows about the page it sent down. Well, CDD is all about sending back data that wasn't in the page to begin with, so this feature needs to be disabled for pages that use it.

That's the good news. :) The bad news (or better news depending on how you see it) is that this should have been easier to debug. CDD tries to populate the list with error details when an error occurs (see _onMethodError), but it doesn't because a change some time ago to use name/value pairs for the data type wasn't applied to the error methods. I've logged this for fixing in the next release.

But for now, your issue should be trivially solvable by flipping EnableEventValidation as I note above.

Thanks!


Fantastic - that did the job!

Thanks
Andrew


nice1 David,

that had really thrown me, thought it was a vb.net thing. the debugging experience on this could definitely be improved on but at least it's in the forums.

thanks

I've been trying to get this example to work so as I can use similar in my own pet project.

Would anyone be kind enough to tell\show me how to create the "Projects" and "FixFor" objects which are defined in the App_Code folder.

I'm getting errors on this line

ForEach myProjectAs ProjectIn Project.GetData

How do I define Project in the TableAdapter?

Rgds

DOShea


Hi,

My parent dropdown itself is not population. I addedEnableEventValidation="false" in page tag. Still no luck.

If i work in " atlas web project", I am able sccess with cascading dropdown. But if i try to do with existing project, i am not able to. No error but first dropdown itself not populating.

I added in web.config

<

pages>

<

controls>

<

addnamespace="Microsoft.Web.UI"assembly="Microsoft.Web.Atlas"tagPrefix="atlas"/>

<

addnamespace="Microsoft.Web.UI.Controls"assembly="Microsoft.Web.Atlas"tagPrefix="atlas"/>

</

controls>

...

</

pages>

This is my aspx page code:

<%

@.PageLanguage="VB"AutoEventWireup="true"CodeFile="Default.aspx.vb"Inherits="_Default"EnableEventValidation="false" %>

<%

@.RegisterAssembly="AtlasControlToolkit"Namespace="AtlasControlToolkit"TagPrefix="atlasToolkit" %>
<formid="form1"runat="server"><atlas:ScriptManagerID="ScriptManager1"runat="server"/><div><asp:DropDownListID="DropDownList1"runat="server"></asp:DropDownList><asp:DropDownListID="DropDownList2"runat="server"></asp:DropDownList></div><atlasToolkit:CascadingDropDownID="CascadingDropDown1"runat="server"><atlasToolkit:CascadingDropDownPropertiesTargetControlID="DropDownList1"Category="Make"PromptText="Please select a make"ServiceMethod="GetDropDownContentsPageMethod"/><atlasToolkit:CascadingDropDownPropertiesTargetControlID="DropDownList2"Category="Model"PromptText="Please select a model"ServicePath="CarService.asmx"ServiceMethod="GetProductGroups"ParentControlID="DropDownList1"/></atlasToolkit:CascadingDropDown></form>

.Vb File:

<WebMethod()> _

PublicFunction GetDropDownContentsPageMethod(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()

Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)

values.Add(

New CascadingDropDownNameValue("A","1"))

values.Add(

New CascadingDropDownNameValue("B","2"))

values.Add(

New CascadingDropDownNameValue("C","3"))Return values.ToArrayEndFunction

My WebService (CarService.vb):

<WebMethod()> _

PublicFunction GetProductGroups(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()Dim kvAs StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)Dim ProvinceIdAsIntegerIf (kv.ContainsKey("Make")And Int32.TryParse(kv("Make"), ProvinceId))ThenIf ProvinceId = 1Then

values.Add(

New CascadingDropDownNameValue("a","1"))ElseIf ProvinceId = 2Then

values.Add(

New CascadingDropDownNameValue("b","1"))EndIfEndIfReturn values.ToArrayEndFunction

Any help is highlyAppreciated.

Regards

kant.


My reply from the private email about this issue:

"The web.config for an Atlas has additional settings that aren't present in a default web.config. It sounds like you need to add one or more of those settings to your site's web.config. You might find the windiff utility helpful in identifying the changes. Hope this helps!"


Thanks David. I am able to solve by adding aditional attributes.

I have another prob with in the same page. I added a gridview to that page having Edit & Delete buttons.

When ever my page is postback(by clicking button or by grid events ) , it's refreshing twice. Any Idea?

I am usingCollapsiblePanel, CascadingDropDownin that page.

kindly reply me if you come across this probulem.

Regards

Kant.


Hi,

This is my scenario.

In production server (win2003 with IIS 6.0, asp.net 2.0 and asp.net 1.1 coexist),
My drop downs appear blank if I try to use web services to provide the data.
If I use built in page methods and I got 'sys' is undefined.

In development pc, (XP with IIS 5.1, asp.net 2.0 and asp.net 1.1 coexist),
Both web services and page methods work without any problem.

Web.config in both machine were identical.

Does anyone have any idea why?

Thanks in advance.

Michael


"Sys undefined" suggests that Atlas itself may not be installed/configured correctly on that server.

CascadingDropDown Lists [Method Error 500]

Hi All,

I have recently started to learn AJAX, as well as all web developing. I am trying to read a database using a web service to populate drop down lists. I have searched through hundreds of posts and tried everything I found. The most common fix I found was to add System.Web.Script.Services.ScriptService before my class and System.Web.Script.Services.ScriptMethod before my WebMethod. I've tried upping my maxjsonlength. But these haven't fixed my problem. My problem being that on my development machine the app works fine, but on my webserver I get the Method Error 500. It seems like it can't find the asmx file, because, to see if it would even return anything, I took out the database read and put in bogus output.

Could my server be missing some key element to run AJAX? I have installed the Extentions on it. Is there something I have to do to deploy or publish the app? I have been just copying over all the files in my project.

I tried to put a call to the webservice in a page level method like they did on the How do I: cascading .. video, but that didn't work. I received a "BC30002: Type WebService not defined" Error. So that brings me back to thinking the app can't find the asmx file.

Anyone have any ideas?! Thanks for the help!

asmx file code:

Imports System.Web

Imports System.Web.Services

Imports System.Web.Services.Protocols

Imports AjaxControlToolkit

Imports System.Collections.Generic

Imports System.Data<WebService(Namespace:="http://tempuri.org/")> _

<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _

<System.Web.Script.Services.ScriptService()> _

PublicClass WebServiceInherits System.Web.Services.WebService

<WebMethod()> _

<System.Web.Script.Services.ScriptMethod()> _

PublicFunction GetCategory(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()

Dim myListAsNew List(Of CascadingDropDownNameValue)

Dim adapterAsNew DataSet1TableAdapters.sp_GetCategory1TableAdapter

myList.Add(New CascadingDropDownNameValue("test","test"))

Return myList.ToArray

'For Each dr As DataRow In adapter.GetCategory1

' myList.Add(New CascadingDropDownNameValue(dr("Category1").ToString, dr("Category1").ToString))

'Next

'Return myList.ToArray

EndFunction

EndClass

aspx file code:

<%@dotnet.itags.org.PageLanguage="VB"AutoEventWireup="true"CodeFile="Default.aspx.vb"Inherits="_Default"EnableEventValidation="false" %>

<%@dotnet.itags.org.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %> 'DO I REALLY NEED THIS LINE?

<!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">

<asp:ScriptManagerID="ScriptManager1"runat="server"/>

<br/>

<br/>

<div>

<asp:UpdatePanelID="UpdatePanel1"runat="server">

<ContentTemplate>

<asp:DropDownListID="DropDownList1"runat="server"Width="232px">

</asp:DropDownList><br/>

<br/>

<br/>

<cc1:CascadingDropDownID="CascadingDropDown1"runat="server"Category="cat1"LoadingText="Loading..."

PromptText="Select Category"ServiceMethod="GetCategory"ServicePath="WebService.asmx"

TargetControlID="DropDownList1">

</cc1:CascadingDropDown>

<br/>

<br/>

</ContentTemplate>

</asp:UpdatePanel>

</div>

</form>

</body>

</html>

Thanks Again!

Princess

Well, I figured it out. Turns out I had my folders in the wrong place. The way I was referencing the webservice, the App_Code file, App_Data, & Bin folders plus the web.config file have to be at the top level of your application folder.

Mystery Solved!


Thats nice..So mark the answer, so it will help for otheres.

CascadingDropDown List 1-dimensional array error

I'm trying to get the CascadingDropDown from the Atlas toolkit to work with a database. I receive this error at the lineReturn values.ToArray().

Error 1 Value of type '1-dimensional array of AtlasControlToolkit.CascadingDropDownNameValue' cannot be converted to 'AtlasControlToolkit.CascadingDropDownNameValue'

Here is the WebMethod.

<WebMethod()> _

PublicFunction GetMakes(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue

Dim makeAdapterAs CarsTableAdapters.MakeTableAdapter =New CarsTableAdapters.MakeTableAdapter()

Dim makesAs Cars.MakeDataTable = makeAdapter.GetMakes()

Dim valuesAs List(Of CascadingDropDownNameValue) =New List(Of CascadingDropDownNameValue)()

ForEach drAs DataRowIn makes

Dim makeAsString =CStr(dr("Make"))

Dim makeIdAsInteger =CInt(dr("MakeID"))

values.Add(New CascadingDropDownNameValue(CStr(dr("Make")), dr("MakeID").ToString()))

Next dr

Return values.ToArray()

EndFunction

Any Ideas?

Rgds

Dave

Replace

PublicFunction GetMakes(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue

With

PublicFunction GetMakes(ByVal knownCategoryValuesAsString,ByVal categoryAsString)As CascadingDropDownNameValue()

CascadingDropDownNameValue() is an array, butCascadingDropDownNameValue is not


Thanks lotusinriver. It works perfectly now.

Dave


You are very welcome.