Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model-bind POST with Array of objects in NancyFx

I have a json object with the following structure

{
 ContainerType: "Box",
 Items : [{Name: "Coin", Amount: 5}, {Name: "Spyglas", Amount : 1}]   
}

This object has an representation in the Nancy backend system:

public string ContainerType {get; set}
public IEnumberable<Item> Items {get; set}

where Item (as expected) is a very simple object with public properties:

public string Name {get; set;}
public double Amount {get; set;}

My problem is that when I receive the Post in my module (based on NancyModule) only the string property is being binded in this line of code:

var model = this.databind<MyContainerModel>();

I've tried with changing list types to more specific (List<MyContainerModel>), to Arrays (MyContainerModel[]), but nothing seems to work.

The data-binding examples in the demo section of the git-repo for Nancy only deals with deserialization of ints, but my question is for the deserialization of arrays with javascript objects.

Any ideas?

Thanks!

like image 596
pardahlman Avatar asked Oct 22 '12 18:10

pardahlman


1 Answers

After a few hours I found the solution. The problem was not the Nancy part of it, it was that my ajax post did not have the right headers. adding contentType and dataType did the trick:

$.ajax({
    url: '/add',
    type: 'POST',
    data: normalModel,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',

})

Hope this helps future readers!

like image 194
pardahlman Avatar answered Oct 22 '22 13:10

pardahlman