Ray
Ray

Reputation: 4108

Calling WCF service from jQuery Ajax using POST method

I have a 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 a 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>

Once ajax invoke AddUser method LoginId and Name value is set in AddUser method's two parameter, however, What I want to do is having a method signature as below

public User AddUser(User user)

Of course, User class have LoginId and Name properties in it.

How to bind client's parameter to user instance automatically without setting the value manually?

Upvotes: 7

Views: 13039

Answers (1)

Ray
Ray

Reputation: 4108

I found the solution by myself

I should wrap the json data with object name as follow :

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

Upvotes: 4

Related Questions