Reputation: 3014
Im trying to send a jSon object to a WebApiController and deserialize it to an object but it just gives me an empty object with zero and null.
Id much rather do model binding though but that does not seem to work in Webappi like it does with AJAX call to a normal MVC controller ?
Javascript (jQuery)
var data = {
siffra : 23,
text : "Meddelande från andra sidan!"
}
$.ajax({
url: "api/Stuff/PostStuff",
method: "POST",
data: JSON.stringify(data),
success: function (result) {
console.log("SUCESS: " + result);
},
error: function (data) {
console.log("error: " + data.responseText);
}
});
WebApiController method
public string PostStuff(JObject jsonObject)
{
Stuff stuff = JsonConvert.DeserializeObject<Stuff>(jsonObject.ToString());
return "thanks";
}
public class Stuff
{
public int siffra;
public string text;
}
JObject before deserialization: {"{\"siffra\":23,\"text\":\"Meddelande från andra sidan!\"}": ""}
Upvotes: 0
Views: 23
Reputation: 1134
Insted of JObject use Stuff model
public string PostStuff(Stuff stuff)
{
return "thanks";
}
WebApi should serilize it automaticly.
Edit
And make sure that ajax send proper json like this one:
{
"siffra" : 23,
"text" : "Meddelande från andra sidan!"
}
Edit 2 Try this call
var data = {
siffra : 23,
text : "Meddelande från andra sidan!"
}
$.ajax({
url: "api/Stuff/PostStuff",
method: "POST",
data: data,
success: function (result) {
console.log("SUCESS: " + result);
},
error: function (data) {
console.log("error: " + data.responseText);
}
});
Upvotes: 1
Reputation: 109100
{"{\"siffra\":23,\"text\":\"Meddelande från andra sidan!\"}": ""}
That is a JSON object with a single property named {\"siffra\":23,\"text\":\"Meddelande från andra sidan!\"}
with the empty string for its value. This is nothing like the Stuff
type.
Which does not match the quoted JS code so you've not included something.
Upvotes: 0