Reputation: 3673
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 fields' 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 into 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 script:
//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");
}
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. How do I make a method which can be called by JavaScript? I may have to use WebInvoke
for this.
Upvotes: 1
Views: 4223
Reputation: 60580
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.
Upvotes: 6
Reputation: 27811
If you're submitting a JSON object, add the following option to $.ajax
:
contentType: "application/json; charset=utf-8",
Upvotes: 0