Search code examples
c#jqueryajaxjsonwebmethod

Calling simple AJAX WebMethod always results in "fail" callback


Below code is my server side code. (C#)

            [WebMethod]
            public static string InsertCV(string edu)
            {             
                return "";
            }

And Below code is my client side code. (ASP.NET)

           var edu = {"education":[{"university":"111","speciality":"222","faculty":"333","degree":"444","start":"555","end":"666"}]}

            var post = $.ajax(
             {
                 type: "POST",
                 data: edu,
                 url: "Add_CV.aspx/InsertCV",
                 contentType: "application/json; charset=utf-8",
                 dataType: "json",
                 async: true,
                 cache: false
             })
            post.done(function (data, teStatus, jqXHR) {
                if (data.d == "")
                { alert("ok"); }
            });
            post.fail(function (jqXHR, e) {
                alert("error");
            });

I would like to send user's data to server with ajax post method. But everytime post.fail() function executes. Please help me that where is my mistake. May be in server side InsertCV(string edu) , string is not appropriate for this situtate. I don't know.


Solution

  • This:

    public static string InsertCV(string edu)
    

    is expecting a single parameter called edu that is of type string. Your AJAX call is instead passing in an un-named JavaScript object, which is not a string. The framework code that is trying to parse the request is never matching your InsertCV method at all, and eventually gives up with a 500 - Internal Server Error result.

    To pass a complex structure like this into a WebMethod you need to define a compatible .NET class to deserialize into. For instance:

    // outer type for the parameter
    public class EduType
    {
        public Education[] education;
    
        // inner type for the 'education' array
        public class Education
        {
            public string university;
            public string speciality;
            public string faculty;
            public string degree;
            public string start;
            public string end;
        }
    }
    
    [WebMethod]
    public static string InsertCV(EduType edu)
    {
        return edu == null ? "null" : string.Format("{0} Items", edu.education.Length);
    }
    

    If the JSON string will deserialize into this format then this method is the one that should get called.