0

I am trying to make an AJAX call to fill a dropdown when a value is selected in another dropdown. Currently, I am getting a SyntaxError: Invalid Character error, but if I remove the "dataType: json", I get this mess that looks like HTML code. The dropdown must be bound using value and text pairs. This is my ASPX code related to the dropdown:

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master"      CodeBehind="Request.aspx.vb" Inherits="NDBEDP.Request" MaintainScrollPositionOnPostback="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        $('.entityDrop').live('change', function (event) {
            loadStateDrop()
        });

        var loadStateDrop = function () {
            var data = "{'entity':'"+ $('#<%=ddlEntity.ClientID%> option:selected').val()+"'}"
            alert("before ajax(), val: " + $('#<%=ddlEntity.ClientID%> option:selected').val());
            $.ajax({
                type: "POST",
                url: "Request.aspx/loadStates",
                datatype: "JSON",
                data: data,
                contentType: "application/json; charset=utf-8",
                success: function (list) {
                    alert(list);
                    $('.stateDrop').empty()
                    $.each(list, function (element) {
                        var optn = document.createElement("OPTION");
                        optn.text = element.StateAbbr;
                        optn.value = element.StateID;
                        $('.stateDrop').append(optn);
                    });
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error updating dropdowns: " + errorThrown);
                }
            });
        };
    </script>
    <asp:panel ID="userInput" runat="server">
        <asp:panel id="userInformation" runat="server" BorderStyle="None" style="margin-bottom: 0px">
            <asp:DropdownList cssClass="entryField, entityDrop" ID="ddlEntity" runat="server" Width="95%"></asp:DropdownList>
            <asp:DropDownList cssClass="entryField, stateDrop" ID="ddlExpenseState" runat="server" Width="18%"></asp:DropDownList>
            <asp:DropDownList ID="ddlExpensePeriod" runat="server" cssClass="entryField" Width="50%"></asp:DropDownList>
            <asp:DropDownList ID="ddlExpenseYear" runat="server" cssClass="entryField" Width="20%"></asp:DropDownList>
        </asp:panel>
    </asp:panel>
</asp:Content>

This is my VB.Net code:

Imports NDBEDP.StringExtensions
Imports NDBEDP.DropdownExtensions
Imports NDBEDP.GridViewExtensions
Imports System.IO
Imports System.Web.Services
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization

Public Class Request
    Inherits System.Web.UI.Page

    <WebMethod()> _
    Public Shared Function loadStates(entity As Integer) As Dictionary(Of String, Integer)
        Dim expenseStates As DataSet = (New RequestBus).getExpenseStates(entity)
        Dim returnStates As New Dictionary(Of String, Integer)
        For i As Integer = 0 To expenseStates.Tables(0).Rows.Count - 1
            returnStates.Add(expenseStates.Tables(0).Rows(i).Item("StateAbbr"), expenseStates.Tables(0).Rows(i).Item("StateID"))
        Next
        Return returnStates
    End Function
End Class

Let me know if you need to see any other code to help.

I have tried doing this through WebServices, but couldn't get that to work either. As soon as I included a WebService and hooked it up properly, before adding any of my own code, I got: JavaScript critical error at line 3, column 1 web service script1002 syntax error. I would prefer to do this in a WebService, but I'm open to anything that I can get to work.

Does anyone know what I'm doing wrong here?

Edit: Changed to match current code

2 Answers 2

0

First off, you do not need to serialize the data coming back from your ASP.NET AJAX Page Method, as it JSON serializes the data by default.

Second, why are you not returning a type from you method? It is a Function and there is no return type declared. It appears you want to return a List(Of T) so that you can loop through the results client-side.

Here is an example page method that returns the current time as a String:

<WebMethod> _
Public Shared Function GetDate() As String
    Return DateTime.Now.ToString()
End Function

Please read this to become more familiar with Using jQuery to directly call ASP.NET AJAX page methods

Sign up to request clarification or add additional context in comments.

18 Comments

I couldn't get it to work with a return type either. I tried returning a Dictionary(Of String, Integer) and, with or without the dataType in the AJAX call, I'm still getting the HTML mess.
You are not sending any data via the .ajax() call to the page method.
Updated answer with blog entry for how to use jQuery .ajax() and ASP.NET AJAX Page Methods together.
I guess I deleted that accidentally in all my changes. I added it back in, but it didn't change the result.
Update your question with the latest code you have for both AJAX code and page method code.
|
0

Here's the final jQuery code:

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master"      CodeBehind="Request.aspx.vb" Inherits="NDBEDP.Request" MaintainScrollPositionOnPostback="true" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        $('.entityDrop').live('change', function (event) {
            loadStateDrop()
        });

        var loadStateDrop = function () {
            var data = "{'entity':'"+ $('#<%=ddlEntity.ClientID%> option:selected').val()+"'}"
            $.ajax({
                type: "POST",
                url: "Request.aspx/loadStates",
                datatype: "JSON",
                data: data,
                contentType: "application/json; charset=utf-8",
                success: function (list) {
                    $('.stateDrop').empty();
                    if (list.hasOwnProperty("d")) {
                         $.each(list.d, function (key, value) {
                             var optn = document.createElement("OPTION");
                             optn.text = key;
                             optn.value = value;
                             $('.stateDrop').append(optn);
                         });
                     }
                     else {
                         $.each(list, function (key, value) {
                             var optn = document.createElement("OPTION");
                             optn.text = key;
                             optn.value = value;
                             $('.stateDrop').append(optn);
                         });
                     }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("Error updating dropdowns: " + errorThrown);
                }
            });
        };
    </script>
    <asp:panel ID="userInput" runat="server">
        <asp:panel id="userInformation" runat="server" BorderStyle="None" style="margin-bottom: 0px">
            <asp:DropdownList cssClass="entryField, entityDrop" ID="ddlEntity" runat="server" Width="95%"></asp:DropdownList>
            <asp:DropDownList cssClass="entryField, stateDrop" ID="ddlExpenseState" runat="server" Width="18%"></asp:DropDownList>
            <asp:DropDownList ID="ddlExpensePeriod" runat="server" cssClass="entryField" Width="50%"></asp:DropDownList>
            <asp:DropDownList ID="ddlExpenseYear" runat="server" cssClass="entryField" Width="20%"></asp:DropDownList>
        </asp:panel>
    </asp:panel>
</asp:Content>

This is my VB.Net code (I probably don't need all of the includes):

Imports NDBEDP.StringExtensions
Imports NDBEDP.DropdownExtensions
Imports NDBEDP.GridViewExtensions
Imports System.IO
Imports System.Web.Services
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization

Public Class Request
    Inherits System.Web.UI.Page

    <WebMethod()> _
    Public Shared Function loadStates(entity As Integer) As Dictionary(Of String, Integer)
        Dim expenseStates As DataSet = (New RequestBus).getExpenseStates(entity)
        Dim returnStates As New Dictionary(Of String, Integer)
        For i As Integer = 0 To expenseStates.Tables(0).Rows.Count - 1
            returnStates.Add(expenseStates.Tables(0).Rows(i).Item("StateAbbr"), expenseStates.Tables(0).Rows(i).Item("StateID"))
        Next
        Return returnStates
    End Function
End Class

Edited to take advantage of this article

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.