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?
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()
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With