Call a WCF service from jQuery Ajax using the POST method

I have the following WCF method

[OperationContract] [WebInvoke(Method = "POST", UriTemplate = "UserService/AddUser", BodyStyle = WebMessageBodyStyle.WrappedRequest)] public User AddUser(string LoginId, string Name) { var user = input; // Some business logic here return user; } 

And I have jQuery Ajax client code as below

 <script type="text/javascript"> $(document).ready(function () { $("#submit").click(function () { var input = { LoginId: $("#LoginId").val(), Name: $("#Name").val() }; $.ajax({ cache: false, type: "POST", async: false, url: "http://localhost:2000/UserService/AddUser", data: JSON.stringify(input), contentType: "application/json", dataType: "json", success: function (userViewModel) { var user = userViewModel; alert(user); } }); }); }); </script> 

As soon as ajax calls the AddUser method, LoginId and Name are set in the AddUser two method parameter, however, what I want to do is to have the method signature as shown below

 public User AddUser(User user) 

Of course, the User class has LoginId and Name properties.

How to bind a client parameter to a user instance automatically without manually setting a value?

+8
jquery wcf
source share
1 answer

I found a solution myself

I have to wrap json data with an object name like this:

  var input = { "user": { "LoginId": $("#LoginId").val(), "Name": $("#Name").val() } }; 
+5
source share

All Articles