ko.utils.postJson, MVC3, and GUIDs

612 views
Skip to first unread message

Dubdiz

unread,
Jun 8, 2011, 5:46:17 PM6/8/11
to KnockoutJS, jde...@gmail.com
Hi. Love the framework; captures and leads the direction of web dev
perfectly IMHO.

I'm having an issue that I don't believe to be the fault of
knockout.js, but any direction anyone can provide is appreciated. I am
using ko.utils.postJson to post to an MVC 3 action, and the JSON
Provider Factory is doing just fine on all of my properties except the
unique ID's which are coming over as empty. I stepped the MVC 3 code
and at some point backslashes are getting added around the GUID and
never taken off. The form you generating in the postJSON method never
adds the backslashes, so I don't know if it can be solved at the
client level. What it ends up looking like is "\"37991423-
bd69-4b2f-93bd-14efa4892d16\"" and it throws the exception {"Guid
should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-
xxxxxxxxxxxx)."} when ValueProviderResult.ConvertSimpleType tries to
convert it.

Again I appreciate any recomendations. My next step at this point is
to get full build with the MVC 3 source and see whether a custom
Provider Factory or other add in does the job, or just give up and go
with int ID's.

Stacey Thornton

unread,
Jun 8, 2011, 5:57:20 PM6/8/11
to KnockoutJS
Since I've been tackling this for a lot of people lately, I'll take it
here too.

What is happening is that ko.utils.postJson doesn't work like an
$.ajax call. postJson creates a new DOM element that is an HTML
<form>, and gives it the action of your original form, and gives it a
single <input> field that has the value of your model serialized as
JSON.

So here is what goes on...

You create your data [OK]
You click save [OK]
New HTML Form is Created [OK]
HTML Input Element is set to JSON string [OK]
HTML Form posts to server [.... .!!!]

MVC tries to 'Encode' the JSON in the string, so it does not see it
properly. So while you THINK you are posting a model, you're actually
posting a string. The Controller just gets a FormCollection[0] == Your
JSON data Re-Encoded.

To get around this, you need a Model Binder that is smarter than the
default Json binder. You can use this one.

https://gist.github.com/1015164

It is the first part of the code. This entire gist shows the whole
process of creating a project in ASP.NET MVC 3.0 that uses Json Model
Binding using postJson.


You do not need to take all of these steps if you use $.ajax, since
you can set the content type, and it is a direct 'post' to the
controller action. The default ASP.NET MVC 3.0 Json Model Binder will
work for those. This is only applicable to postJson uses.

postJson is useful because you can use things like "return
RedirectToAction" from it, but it caused me a lot of headaches.
Reply all
Reply to author
Forward
0 new messages