I have been having this issue in one of my applications and have stripped it down and set up a small test environment in which the problem still occurs.
I am posting the following object (JSON)
{
"eventName":"Testing from Services",
"tickets":10,
"_date":"10/10/2013",
"_time":"8:00 PM",
"ticketsLocation":"Testing from Services",
"date":"2013-10-11T00:00:00.000Z"
}
using the following ajax call
self.save = function (item, url, success) {
$.ajax({
type: "post",
data: JSON.stringify(item),
contentType: "application/json, charset=utf-8",
traditional: true,
datatype: "json",
url: self.domain + url,
success: success,
error: self.error
});
};
and then binding the data with the following code on the server
var Model = this.Bind<PropertyType>();
where PropertyType
is the correct type (Event
).
Here is the Event
class for reference
public class Event
{
public string EventName { get; set; }
public int Tickets { get; set; }
public Venue Venue { get; set; }
public string TicketsLocation { get; set; }
public DateTime Date { get; set; }
public List<EventRequest> Requests { get; set; }
}
This works perfectly fine in Firefox. In Chrome and IE, Model
ends up being an Event
object with all null values. As far as I can tell (by using Fiddler), the post request is exactly the same between all browsers. I have also tested this on other machines, ruling out my machine and/or browsers as the issue.
Any ideas? I don't understand how the browser affects Nancy model binding...
The simple answer is that your content-type is invalid. There is no such thing as an application/json, charset=utf-8
content type, despite what people might tell you. Even though charset
is a valid, optional, extension to content-type it does not apply to application/json
You can read about this here http://www.ietf.org/rfc/rfc4627.txt?number=4627 under section 6 IANA considerations
The MIME media type for JSON text is application/json.
Type name: application
Subtype name: json
Required parameters: n/a
Optional parameters: n/a
With the additional explanation about encoding
Encoding considerations: 8bit if UTF-8; binary if UTF-16 or UTF-32
JSON may be represented using UTF-8, UTF-16, or UTF-32. When JSON is written in UTF-8, JSON is 8bit compatible. When JSON is written in UTF-16 or UTF-32, the binary content-transfer-encoding must be used.
In short, JSON is already, implicitly, utf-8
. In fact, under section 3. Encoding
it states
JSON text SHALL be encoded in Unicode. The default encoding is UTF-8.
Send in application/json
and you should be set to go
Hope this helps :-)
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