Search code examples
c#jqueryasp.netjavascriptserializerpagemethods

AJAX request not working with ASP.Net C# - 500 server error


I tried this page method code in my ASPX page (ShowUsers.aspx), but the function gave me a 500 server error and does not go in to the success handler.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string GetInfo(string email)
{
    JavaScriptSerializer jss = new JavaScriptSerializer();
    User user = UserService.GetUser(email);
    return jss.Serialize(user);
}

And the JavaScript:

$(document).ready(function() {
  $("#l").click(function() {
    $("#modalUpdate").fadeIn(1000);
    var url = "ShowUsers.aspx/GetInfo";
    var email = "[email protected]";

    $.ajax({
      url: url,
      type: "POST",
      data: "{ email : " + email + " }",
      dataType: "JSON",
      contentType: "application/JSON; charset=utf-8",
      success: function(msg) {
        alert("success");
        var data = JSON.parse(msg.d);
        // do stuff (trimmed)
      },
      error: function(msg, xhr) {
        alert(msg + ", " + xhr.responseText);
      }
    });
  });
});

Can someone help me please?


Solution

  • Your JSON is invalid as you have not enclosed the email-address string inside quotes in JavaScript.

    Programmatic proof that this will cause a server-side exception:

    void Main()
    {
        string email = "[email protected]";
        var postback = new Postback { email = email };
    
        Console.WriteLine(new JavaScriptSerializer().Deserialize<Postback>("{ email : '" + email + "' }")); // email string escaped, ok
        Console.WriteLine(new JavaScriptSerializer().Deserialize<Postback>("{ email : " + email + " }")); // YOUR INPUT, exception Invalid JSON primitive
    }
    
    public class Postback
    {
        public string email { get; set; }
    }
    

    A server-side exception manifests itself as an Internal Server Error, code 500. You should be able to see the exception details in the Windows event viewer.

    So in JavaScript just wrap the email address inside quotes:

    data: "{ email : '" + email + "' }",
    

    Also note that all you need for your web method body is

    public static User GetInfo(string email) {
       return UserService.GetUser(email);
    }
    

    i.e. you do NOT need to spin up a serializer yourself. The Framework selects and spins up the necessary serializer (JSON or XML) based on the request headers.