user3409920
user3409920

Reputation: 47

POST Complex type to WebAPI from jquery

I have a web service

[HttpPost]
[ActionName("ChangePassword")]
public string ChangePassword(Models.User value)
{
    return "";
}

And structure of User class is

public class User
{
    public string Username { get; set; }    
    public string OldPassword { get; set; }    
    public string NewPassword { get; set; }
}

And I am calling this from JQuery

var value = { 'Username': name.val(), 'OldPassword': oldPassword.val(), 'NewPassword': newpassword.val() };
var b = JSON.stringify(value);
$.ajax({
    type: "POST",
    url: "http://tryURL/api/service/ChangePassword",
    async: true,
    cache: false,
    type: 'POST',
    data: JSON.stringify(value),
    dataType: "json",
    success: function (result) {
        alert(result);
    },
    error: function (jqXHR, exception) {
    }
});

Now when I debug the web service, it gives me an object but within the object, all properties are null. I have also tried to put [fromBody] in parameter but it does not work.

Upvotes: 1

Views: 1362

Answers (2)

tlt
tlt

Reputation: 15291

data: 'value=' + JSON.stringify(value)

Upvotes: 0

Murali Murugesan
Murali Murugesan

Reputation: 22619

Try like this, it may work

var value = {};
value.Username=name.val();
//etc

in ajax

data: JSON.stringify(value),//no change

Then remove var b = JSON.stringify(value);

Upvotes: 2

Related Questions