Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling WCF service from jQuery Ajax using POST method

Tags:

jquery

wcf

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?

like image 221
Ray Avatar asked Feb 14 '12 06:02

Ray


Video Answer


1 Answers

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()
            }
        };
like image 60
Ray Avatar answered Sep 23 '22 17:09

Ray