0

I'm using VisualStudio 2008 and have a method on an ASPX page I am trying to call with javascript using jQuery as shown below. I am just getting the page's HTML back. The webmethod is not called. Interestingly, if I change the name of the webMethod to call in the javascript, I still get back the HTML. Not an error saying the webMethod cannot be found.

I've tried changing the data argument to "{ 'dummy':0 }", but that doesn't help.

I've used this strategy without problem in a new VS 2010 app, but can't seem to get it to work on an existing app in VS 2008 that I am adding a page to. (trying to add a twist to an old app) I've looked at what firebug is telling me in firefox, and all looks right.

Any help is greatly appreciated.

C# WebMethod decalaration:

    [WebMethod()]
    public static string getQuestionnaires(int dummy)
    {
        System.Diagnostics.Debug.WriteLine("getQuestionnaires called");
        SqlCommand command = new SqlCommand();
        command.CommandText = "dbo.ws_GetPSQuestionnaire";
        command.CommandType = CommandType.StoredProcedure;
        DataTable dtQuestionnairesRaw = Utilities.ReturnDataSet(command).Tables[0];

        DataTable dtQuestionnaires = new DataTable();
        dtQuestionnaires.Columns.Add(new DataColumn("questionnaireID", typeof(int)));
        dtQuestionnaires.Columns.Add(new DataColumn("name"));

        foreach (DataRow dr in dtQuestionnairesRaw.Rows)
        {
            DataRow drNew = dtQuestionnaires.NewRow();
            drNew["questionnaireID"] = dr["questionnaireID"];
            drNew["name"] = Utilities.RemoveHTMLTags(dr["name"].ToString());
            dtQuestionnaires.Rows.Add(drNew);
        }
        dtQuestionnaires.AcceptChanges();

        return (JsonConvert.SerializeObject(dtQuestionnaires, Formatting.Indented));
    }

I am calling it with this javascript. My error function is ALWAYS called.

    $(document).ready(function() {
        var request = $.ajax({
            type: "POST",
            url: "/crs4/admin/editPSQuestionnaire.aspx/getQuestionnaires",
            contentType: "application/json; charset=utf-8",
            data: "{ 'dummy':'0' }",
            dataType: "json",
            success: populateQuestionnaires,
            error: AjaxFailed
        });
    });
4
  • "{ 'dummy':'0' }", should be valid JSON notation in the string '{ "dummy":"0"}', - you also have to have specific web.config options set to call page methods (as opposed to web service methods only). Can you explain why you manually serialize vs letting the .net do that for you by returning a valid item such as a list? Commented Jun 25, 2012 at 18:49
  • I'm not sure what you mean. Don't I need to pass valid JSON to the web method? How would I pass it otherwise? Once this is working, I will have other methods I wish to call with different parameters accordingly. Commented Jun 27, 2012 at 14:07
  • what I posted was for the purpose of simply getting it to work. I'll use a function that accepts an array of parameters for use elsewhere on my page. Commented Jun 27, 2012 at 14:38
  • check the URL for the 401 error Commented Jun 27, 2012 at 16:05

1 Answer 1

1

Let's get this down to very simple to verify your configuration:

create a simple class to return:

public class myReturn
{
    /// web service/webmethod needs 0 parameter constructor
    public myReturn()
    {
    }
    public myReturn(string returnValue)
    { 
        ReturnValue = returnValue;
    }
    public string ReturnValue;
}

declare your web method to use the class:

[WebMethod()]      
public static myReturn getQuestionnaires(int dummy)      
{
   return new myReturn("howdy");
}

Call it:

//set up the ajax with error so we see what is going on.
// the following syntax requires jquery 1.5 or later for the
// converters used for asp.net
$.ajaxSetup({
    data: "{}",
    dataType: "json",
    type: "POST",
    contentType: "application/json",
    converters: {
        "json jsond": function(msg) {
            return msg.hasOwnProperty('d') ? msg.d : msg;
        }
    },
    error: function(xhr, textStatus, errorThrown) {
        var errorMessage = ("Ajax error - " + this.url + " | "
           + textStatus + " | " + errorThrown + " | " 
           + xhr.statusText + " | " + xhr.status);
        alert(errorMessage);
    }
});

var pString = '{"dummy":0}';
$.ajax({
    data: pString,
    url: "/crs4/admin/editPSQuestionnaire.aspx/getQuestionnaires",
    success: function(msg) {
        alert(msg);
    }
});

EDIT: you might need this in the web config:

<httpModules>
    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
Sign up to request clarification or add additional context in comments.

17 Comments

Okay, I created a new empty page to run this test against called "Tester". Changed the URL to use that page instead. Got this error: Ajax error - /crs4/admin/Tester.aspx/getQuestionnaires | parsererror | SyntaxError: JSON.parse: unexpected character | OK | 200
If you run the debugger to the line where it returns, did it actually get the 0 to the method as expected? or simply change it to another number like 2 in the pString if that is confusing :)
Also, be sure you have your web.config file set up for this...calling aspx.net page methods - lots of articles on that available. I make a wild assumption about 3.5 and not 2.0 .net but if you use 2.0 you will need script manager as well.
One other thought, you are simply returning a string and you might change the dataType to "jsond"
The web app has an asmx page included for web services. So I would think that the web.config file is fine. It is .net 3.5. I put in a diagnostics.debug.writeline as the first line in the web method and it never writes anything. Adding a breakpoint on the return line doesn't get hit either. It looks like the web method isn't being called here either. Changed the dataType in the .ajaxSetup to jsond and I get the same error.
|

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.