views:

583

answers:

2

I am Developing a Registration Form in ASP.Net in Which i am using client side scripting.So I used jQuery.ajax method to POST all field's data to server through a ASP.Net Web-Service.But when i execute the Jquery.ajax method it calls error function.I tried to debug it using Firebug in Firefox.It showed error 500 Internal Server Error.Now what i assume is that to Insert Data in to a WebService I need to use a POST method and similarly i need a function on Server Side inside Webservice which can be invoked using POST method.I am providing few snippets of code to illustrate what i have done.

//My Client Side Function
function registerUser()
{
    var User = {
      FirstName:$get("txtFirstName").value,
      LastName:$get("txtLastName").value
      .
      .
      //and so on....This way I creat my json object to POST on server
      };

      //jQuery to POST Data
      jQuery.ajax({
        type:"POST",
        url:"Service/UserRegistration.asmx/InsertUser",
        data:User,
        success:notifyUser,
        error:setErrorField
      });

}

//Function for Success Complition function notifyUser(msg) { alert("Registration Successfull"); }

-------Now this was my client script.Now i'll show you my web Service on the server--------

//My C# Web Service Logic
[WebMethod]
public void InsertUser(User use)
{
      FreeUser us = new FreeUser();
      us.FirstName = use.FirstName;
      .
      .
      //and so on
}

Now What i suppose is that POST method requires WebInvoke class as attribute.so if any one can suggest how do i make method which can be called by a javascript.I may have to use WebInvoke for this.

Thank You.

A: 

If you're submitting a JSON object, add the following option to $.ajax:

contentType: "application/json; charset=utf-8",
Traveling Tech Guy
+4  A: 

If you have ASP.NET AJAX available on the server-side (ASP.NET 2.0 + ASP.NET AJAX Extensions v1.0 or ASP.NET 3.5+), I've found that the easiest way to do it is to use JSON between the client and server-side. You'll just need to add the [ScriptService] attribute to your service and then use this form for calling the service:

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "WebService.asmx/WebMethodName",
  data: "{}",
  dataType: "json"
});

For more info, see the full post here: http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/

In order to provide a JavaScript object as you are in that example code, you'll also need to use JSON.Stringify to generate an appropriate JSON string to pass to the server-side.

Dave Ward