views:

34

answers:

4

I have ajax request to post data to asmx webservice, how will i post multiple data values as json data to that url

 $.ajax(
        {
            type:"POST",
            url:"AjaxService.asmx/CheckUserNameAvailability",
            data:"{\"userName\":\"" + userName + "\"}",
            dataType:"json",
            contentType:"application/json",
            success: function(response) 
            {
                if(response.d == true) 
                {
                    $("#display").text("username is available and updated to database");
                     $("#display").css("background-color","lightgreen");
                }
                else
                {
                  $("#display").text("username is already taken");
                     $("#display").css("background-color","red");
                }
            }
        });

This is the particular webservice code where i retrieve the username ,how can i retrieve many values passed from that paticular url ,for example i have to retrieve username ,password, email,phoneno etc...

    public class AjaxService : System.Web.Services.WebService
    {
        [WebMethod]
        public bool CheckUserNameAvailability(string userName)
        {
            List<String> userNames = new List<string>() { "azamsharp", "johndoe", "marykate", "alexlowe", "scottgu" };

            var user = (from u in userNames
                        where u.ToLower().Equals(userName.ToLower())
                        select u).SingleOrDefault<String>();

            return String.IsNullOrEmpty(user) ? true : false; 

        }

    }
}
+1  A: 

Try using the JSON.stringify method which will take care of properly encoding data instead of concatenating strings:

url: 'AjaxService.asmx/CheckUserNameAvailability',
data: JSON.stringify({ 
    userName: userName, 
    password: 'foo', 
    email: '[email protected]' 
}),
dataType: 'json'
Darin Dimitrov
You will need the json2.js to stringifiy, http://www.json.org/json2.js
chriszero
Thank you very much for the reply can i write c# code behind in webservice .asmx file , to fetch the json data from the ajax request and place the extracted data to sql server
mahesh
A: 

If you are posting data to the webservice you just pass multiple parameters like this:

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

You also need to change your webmethod:

public bool CheckUserNameAvailability(string userName, string password, string email)
Daniel Dyson
What if the username contains some character that could break JSON?
Darin Dimitrov
That's the reason to use JSON.stringify. It do all the escaping
chriszero
Good point @Darin although I tend to perform my client side validation before making the AJAX call, and then validate again on the server.
Daniel Dyson
@Daniel, so you are removing all the dangerous characters from the username/password? What if it **has** to contain a dangerous character?
Darin Dimitrov
Not removing. Validating. If it is illegal (outside the specific rules of the website) then it doesn't even get submitted. Don't get me wrong, I think your idea to use an escaping script is a good one. Hence the upvote. I was just explaining why I didn't have it in my answer. I generally restrict usernames to only allow alphanumeric and a few very specific other characters. But yes, if you don't have control over those specific rules, then escaping is a good idea.
Daniel Dyson
thank you very much for reply ,it helped me a lot
mahesh
Don't forget to mark the correct answer by clicking the empty tick image below the voting buttons. Yuo get points for marking an answer as correct too.
Daniel Dyson
+1  A: 

Well, your service method can accept string array to get multiple user names as i/p.

public bool CheckUserNameAvailability(string[] userNames)

To pass values from java-script, use java-script array notation. For example,

   data: '{ userNames: ["Name1", "Name2", "Name3"] }'

For your second question, method can return an user object with all relevant properties for the requested user. For example, you can have a another method

public User GetUserDetails(string userName)

where User is class having relevant properties.

To invoke this service method, you have to update URL from your JS as follows:

url:"AjaxService.asmx/GetUserDetails"

Your service can have multiple web methods and you need to change URL accordingly. Now, the returned user object can be used in JS as any javascript object e.g. use response.d.Name to get user name, response.d.Email for email etc.

VinayC
Thank you for reply
mahesh
can i write c# code in webservice, so that i will place the json data obtained from the url to sql server
mahesh
Umm...not sure what you mean! You are already writing C# code in web service. JSON data will be automatically get deserialized to .NET types when call reaches to your web method. If you want to log raw JSON data that was passed to the service then your best bet would be a intercepting HTTPModule or BeginRequest in global.asax.
VinayC
+1  A: 

Try this: http://www.dotnetspeaks.com/DisplayArticle.aspx?ID=80

Sumit