0

In the process of converting a page from normal postbacks to AJAX-calls (using JavaScript to load/control the UI entirely and use ASP.Net strictly as a backend), I found myself wanting to replace a GridView with a AJAX-sourced dataset.

I currently use DataTables to prettify the GridView, and there exists an option in the API to use AJAX to remotely source the data for the table. The API needs a JSON object returned, although it appears that I can supply a callback for the fnServerData option which would allow me to convert the XML response to the requisite JSON datasource.

"So", I thought, "I might as well slap together a <WebMethod()> to return the datasource..." and while I've written several <WebMethod()> functions in the past, I've always added a new ASMX file (with a custom class to drive it) or extended an existing one where it made sense to do so. With this specific page, there is no need to make the datasource for this table accessible outside the context of the page, so I thought I would try to add the <WebMethod()> to code-behind of the ASPX page.

There appear to be several examples on the web of programmers successfully pulling off what I have been pulling my hair out over.

I have followed every example that I can find and none are working for me. I have put together an extremely simple example in the hopes that someone can either point out where I'm going wrong or confirm that ASP.Net 2.0 simply won't work in this manner.

ASP Markup:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="AJAXText.aspx.vb" Inherits="_AJAXText" %>

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

    </div>
    </form>
    <script type="text/javascript" src='<%=Helpers.ToAbsoluteURL("~/_cs/js/jquery-1.6.4.min.js") %>'></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: window.location.href + "/Hello",
                data: {
                    "What": "World"
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    $('div').text(textStatus);
                },
                complete: function (jqXHR, textStatus) {
                    $('div').text(textStatus);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('div').text(textStatus);
                }
            });
        });
    </script>
</body>
</html>

Code-Behind:

Imports System.Web.Services

Partial Class _AJAXText
    Inherits System.Web.UI.Page

    <WebMethod()> _
    Public Shared Function Hello(ByVal What As String) As String
        Dim msg As String = "Hello, " & What & "!"
        Return msg
    End Function
End Class

I have tried several little changes to the above, and in every case the AJAX call returns the following:

<!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>
        <title>Untitled Page</title>
    </head>
    <body>
        <form name="form1" method="post" action="AJAXText.aspx?What=World%2fHello"
        id="form1">
            <div>
                <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJOTU4MjMyMzI1ZGQT/2jrJ+cI2ERazl2Hw7l7TI5XiA==" />
            </div>
            <div></div>
        </form>
        <script type="text/javascript" src='http://localhost:3719/Maggie/_cs/js/jquery-1.6.4.min.js'></script>
        <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: window.location.href + "/Hello",
                data: {
                    "What": "World"
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data, textStatus, jqXHR) {
                    $('div').text(textStatus);
                },
                complete: function (jqXHR, textStatus) {
                    $('div').text(textStatus);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    $('div').text(textStatus);
                }
            });
        });
        </script>
    </body>
</html>

What I expect to be returned is:

<?xml version="1.0" encoding="utf-8"?>
<string>Hello, World!</string>

Does anyone have any ideas:

  1. What I am doing incorrectly?
  2. Or is ASP.Net 2.0 is incapable of using a <WebMethod()> in an ASPX page?
madth3
  • 7,275
  • 12
  • 50
  • 74
pete
  • 24,141
  • 4
  • 37
  • 51
  • Can you describe what not working is? Have you verified if the ajax call is made? – TheGeekYouNeed Apr 06 '12 at 17:52
  • It sounds like you are running into the same issue as here: http://stackoverflow.com/questions/348689/jquery-ajax-with-asp-net-webmethod-returning-entire-page – Philip Rieck Apr 06 '12 at 18:27
  • @TheGeekYouNeed, The AJAX is called and what is returned (as opposed to what I expect returned) is posted above for your perusal. – pete Apr 06 '12 at 18:30
  • @PhilipRieck, Yes, indeed I am. I looked at that prior to posting this question. However when I apply the "accepted" answer to the example above, nothing changes. The behavior of returning the entire HTML of the ASPX remains the same. – pete Apr 06 '12 at 18:32

3 Answers3

1

Looks like your data is being provided incorrectly. Should be:

data: "{' + "What" + ':'" + "World" + "'}",

I singled the "What" and "World" out because I assume those are variable values from elsewhere.

so if:

var x = "World";


.ajax(){
.....
.data: "{'What':'" + x + "'}",

would be correct

HTH

TheGeekYouNeed
  • 7,509
  • 2
  • 26
  • 43
  • I changed the line to read `data: "{'What': 'World'}"` and the entire HTML of the ASPX still comes back. Also, according to http://api.jquery.com/jQuery.ajax/, `data` "is converted to a query string, if not already a string" and the default for `processData` is `true` which leads to "By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string". – pete Apr 06 '12 at 20:35
0

Okay, I finally found the complete answer (and +1 to @TheGeekYouNeed for what turned out to be part of the solution).

ASP.Net 2.0 does not support WebMethod() in an ASPX page out-of-the-box. There were three steps total (for me) to enable support of WebMethod() in an ASPX page.

  1. Download and install Microsoft ASP.NET 2.0 AJAX Extensions 1.0.
  2. Add the following to the <httpModules> section of the <system.web> section in my web.config.

    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

  3. stringify the JavaScript object being passed to the WebMethod() (and ergo, props to @TheGeekYouNeed). jQuery will automatically convert a JavaScript object to key/value pairs for the query string. The AJAX Extensions, on the other hand, effectively require that a JavaScript object be stringified into JSON (not parsed into key/value pairs for POST[ing] or GET[ting]) as the HTTP Content-Type header must be set to application/json. Since jQuery will not convert data of type string, the JavaScript object must first be stringified into JSON. The JSON string can then be passed with impunity to the AJAX Extensions. There's a lot of information about the stringification being necessary on the web, just search for Invalid JSON primitive. Personally, I thought the best explanation came from Dave Ward over at encosia.com.

UPDATE:

I ran into the same problem on my production server (running the .Net 4.0 Framework on IIS7). To correct the problem on the production server, I had to add the following to the web.config under the <configuration> element:

<system.webServer>
    <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>
pete
  • 24,141
  • 4
  • 37
  • 51
0

Exactly working. I was researching this problem since last week. because my local having .NET 4 but due to web server my source has to develop in .Net 2.0

What I have done.

  1. Microsoft ASP.NET 2.0 AJAX Extensions 1.0.
  2. WEB.CONFIG updated/appended exactly what given in [LINK][1] [1]: http://www.asp.net/AJAX/Documentation/Live/ConfiguringASPNETAJAX.aspx
László Papp
  • 51,870
  • 39
  • 111
  • 135
rajar
  • 53
  • 4