I am working through a new project using Knockout.js and the ASP.NET web ApiController. Many of the examples I see perform some manual JSON serialization before posting the data to the server. Additionally, the request content type is equally often set to "application/json".
I am wondering why this is necessary. I'm assuming there's something I haven't yet encountered that makes this either required or at least preferable.
Currently, I am having no issues sending any data I desire to the server using these jQuery ajax options:
cache: false,
traditional: true,
type: 'POST',
Here's sample JS object and corresponding server-side C# model object that POSTs and binds to the ApiController action method just fine.
//JS object
var requestDataObject = {
accountId: vm.accountId,
range: [1, "a'b\"c", 3],
start: new Date(2012, 12, 12)
};
//C# model object
public class RequestData
{
public int AccountId { get; set; }
public string[] Range { get; set; }
public DateTime Start { get; set; }
}
//Action method signature
[HttpPost]
public HttpResponseMessage GetAccountUsage(RequestData requestData){
...
What am I missing?
Historically, GET (and subsequently POST) can only send key-value pairs, and the keys should be unique.
When PHP came, it defined "if a key contains square brackets, let's build an array". This enabled the programmers to call their checkboxes name="chkbox[]"
, let the form submit normally, and read $_POST['chkbox']
as an array. Some other server languages defined, "if a key is repeated in the query string, let's build an array".
If the key names[]=1
was to be supported, why not names[a][b][c]=1
? The servers knew what they should do: Assign names = {a:{b:{c:"1"}}}
.
This enables the programmers to encode objects to query the string, with a few catches:
checkboxes[]=ch1&checkboxes[]=ch2&...
vs. checkboxes=["ch1","ch2",...]
traditional
(or resort to reading from postVars.get("names[]")
on servers that do)With JSON,
null
, ...In short, if you only need to encode key-value pairs, that's what a plain GET or POST excels at. If you need to encode arrays, JSON is definitely worth considering. If you need anything more complex, JSON is the only way to go with some servers.
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