Link to home
Start Free TrialLog in
Avatar of edwbear1976a
edwbear1976a

asked on

USING AJAX CASCADINGDROPDOWN AND WEBSERVICE

Hi , I'm new in Ajax and I want to use Ajax CascadingDropDown with a database but it requieres webservices besides other stuffs  in the sample they call and handle the Database in the same webservice this but I'm used to DAO files to handle the database and in the webservice code I just call the DAO file and it retrieves me an arraylist of entities so I don't have to use the DataRows stuffe..here is the question: is that right? . If so it might decrease the performance?
http://www.asp.net/AJAX/AjaxControlToolkit/Samples/Walkthrough/CCDWithDB.aspx
[WebMethod]
    public CascadingDropDownNameValue[] GetOrdersByEmployee(
      string knownCategoryValues,
      string category)
    {
        StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        int iEmployee;
        if (!kv.ContainsKey("Employee") || !Int32.TryParse(kv["Employee"], out iEmployee))
        {
            return null;
        }

        SqlConnection connection = new
            SqlConnection(@"Data Source=SERVER\SQLEXPRESS;
                Initial Catalog=Northwind;
                Integrated Security=True");

        SqlCommand command =
            new SqlCommand("SELECT OrderID FROM Orders WHERE EmployeeID = " + iEmployee);

        command.Connection = connection;
        connection.Open();

        SqlDataAdapter adapter = new SqlDataAdapter(command);
        DataSet dataSet = new DataSet();

        adapter.Fill(dataSet);
        command.Connection.Close();

        DataTable tbl = dataSet.Tables[0];

        List<CascadingDropDownNameValue> values = new List<CascadingDropDownNameValue>();
        foreach (DataRow dr in tbl.Rows)
        {
            string sOrder = dr["OrderID"].ToString();
            int iOrder = (int)dr["OrderID"];
            values.Add(new CascadingDropDownNameValue(
              sOrder, iOrder.ToString()));
        }
        return values.ToArray();
    }
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

All you need to do is to create an array of CascadingDropDownNameValue, which is just what you described.  You might want to thing about using an SqlDataReader, which is light-weight, forward-only view of the data, which is optimized versus the SqlDataAdapter.

Bob
Avatar of edwbear1976a
edwbear1976a

ASKER

Hi and thanx for your comments
well I use a DataReader (OLEDB , I'm using Oracle DB)  in the DAO (Data Access Object File) and I have no problem to do it all in the same webservice file , the problem is that I've got an error message , even when there's only a dllControl linked as target Control and to be really sure I just replaced the Database Stuff for a Blucle of Strings so it should be easy but..I've got the error:
(I'm using VB cause the View Files(aspx) are in that lenguage, I prefer C# instead cause most of the samples are in that language)
The error !!! (it shows up after the page_init method
========================================================================
Server Error of the  '/Presentation' application .
--------------------------------------------------------------------------------

Null Reference to an Object
Description: anHandle  Excepción at executing the actual  webservice request. Follow the stacktrace
excepcion Detaills.  System.NullReferenceException

StackTrace:

[NullReferenceException: Referencia a objeto no establecida como instancia de un objeto.]
   AjaxControlToolkit.CascadingDropDown.CascadingDropDown_ClientStateValuesLoaded(Object sender, EventArgs e) +111
   AjaxControlToolkit.ExtenderControlBase.LoadClientStateValues() +268
   AjaxControlToolkit.ExtenderControlBase.Page_PreLoad(Object sender, EventArgs e) +28
   System.EventHandler.Invoke(Object sender, EventArgs e) +0
   System.Web.UI.Page.OnPreLoad(EventArgs e) +96
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2780

 


This is the web Service
============================================================================
'// Web Service
<WebService(Namespace:="http://localhost:4643/Presentation")> _
Public Class CarProd1Proc1
    Inherits System.Web.Services.WebService
<WebMethod()> _
    Public Function GetMarke(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
        Dim values As List(Of CascadingDropDownNameValue) = New List(Of CascadingDropDownNameValue)
                Dim i As Integer
                For i = 0 To 10


            Dim Make  As String = "Make-" & i.ToString()
            Dim MakeId As Integer = i

            values.Add(New CascadingDropDownNameValue(Make,MakeId.ToString()))

        Next
        Return values.ToArray()
    End Function
 '//CascadingDropDown in  Aspx Page
===================================================================
 <AjaxControlToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server"
  TargetControlID="ddlCOD_MARCA" Category="Make" PromptText="Select an Item" ServicePath="CarProd1Proc1.asmx"  ServiceMethod="GetMake"  ParentControlID=""/>

===============================================================

Can you find a clue...?
Is just me, or is there a typo?

ServiceMethod="GetMake"
Public Function GetMarke

You have an extra "r" in the web method.

Bob
Sorry .. it was the translation (the original code is in spanish) it's a typo GetMake (GetMarca in spanish)..it has nothing to do with the error problem
Can you find any clue?
I just set the servicemethod as blank  and I Commented out the  GetMake method from the webservice file and I still get the same error message
Could it be the namespace???
ASKER CERTIFIED SOLUTION
Avatar of Bob Learned
Bob Learned
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi and thanx for the comments
well , I'm going to have to download the most current version, but I think that this shouldn't happen even if it wasn't the most recent version.I downloaded the ajaxtoolkit 2 months ago... well I'm going to have to try
Hi I've been debuggin my proyect with AjaxToolkit proyect and I found the unhandled exception

The ddl_cod_marca refers to a simple asp ddl ,  but it's not fill already and actually it's not found by the FindControlMethod but it seems when it want's to clear() it the exception happens...

 private void CascadingDropDown_ClientStateValuesLoaded(object sender, EventArgs e)
        {
            DropDownList dropDownList = (DropDownList)TargetControl;
            dropDownList.Items.Clear(); // HERE IS WHERE IT FAILS !!!!
            string separator = ":::";
            string clientState = base.ClientState;
            int separatorIndex = (clientState ?? "").IndexOf(separator, StringComparison.Ordinal);
            if (-1 == separatorIndex)
            {
                // ClientState is the value to set
                dropDownList.Items.Add(clientState);
            }
            else
            {
                // Parse the value/text out of ClientState and set them
                string value = clientState.Substring(0, separatorIndex);
                string text = clientState.Substring(separatorIndex + separator.Length);
                dropDownList.Items.Add(new ListItem(text, value));
            }        
        }
 
Try this:


private void CascadingDropDown_ClientStateValuesLoaded(object sender, EventArgs e)
        {
            DropDownList dropDownList = (DropDownList)sender;
            dropDownList.Items.Clear();
            string separator = ":::";
            string clientState = base.ClientState;
            int separatorIndex = (clientState ?? "").IndexOf(separator, StringComparison.Ordinal);
            if (-1 == separatorIndex)
            {
                // ClientState is the value to set
                dropDownList.Items.Add(clientState);
            }
            else
            {
                // Parse the value/text out of ClientState and set them
                string value = clientState.Substring(0, separatorIndex);
                string text = clientState.Substring(separatorIndex + separator.Length);
                dropDownList.Items.Add(new ListItem(text, value));
            }        
        }

Open in new window

Could it be cause the ddl is in UpdatePanel? so this way it can't be found?
That is not your code (d'oh).  I'll have to think why that is happening.

Bob
Look at what the unique ID is for the control (View Source from rendered page).  The UpdatePanel is a naming container, and added its part to the ID.  You will need the UniqueID for the control for TargetControl to work.

Bob
I had to move the controls out the update panel, now they can be found. The code above is from the AjaxToolKit CascadingDropDownExtenter.cs. Now it seems to be working out...
Now the ddl shows up but it retrieves me a line in the combo "Method Error 500" even when I fill it with a simple Bucle.
It's weird that I can't debugg the webservice page
You can debug the web service page, but the process is kind of convoluted.  Another approach is to use a Page method.  There is the Smart Tag for the control (arrow in the upper right of the control).  If you click it, you will get an option to create a page method.  The approach for the method is exactly the same as the web service call, but the attributes for the method will be different.  The methods needs to be public static, and the ScriptManager needs EnablePageMethods="true".

Bob
Hi and Thanx for your comments, I'm going to try it and I've read that debugging a webservice page convulter.. but about the webservices . is there a chance that the problem is because the namespace or something like this,? maybe I'm not setting the right namespace url ?
I really don't know what it is, but it doesn't sound like a problem setting the ServicePath and ServiceMethod.

Bob
Hi, do you mean the smart tag of de CascadingDropDown?  I was checking and this options is not enabled..is there another way?
What do you mean that it is not enabled?  Where you running at the time?

Bob
I mean about the CascadingDropDown smart tag.. but you know something ... I was reading about the method error 500 cases and I found a clue and now it's working fine.. I was missing the : [System.Web.Script.Services.ScriptService] at the start of the webservices code (It was
[Windows.Web.Script.Services.ScriptService] instead) now it's working good (for a single dropdownlist now I have to try the children ddls) . well you gave me the clue when I only had an error page that said nothing and you made me see the code of LoadClientStateValues() that when I debugged it let me know where the first error was at. You Deserve and A and the whole score. This is my first webservice and Net Ajax is completly new for me so  I bet soon I will get another questions.