Using Json with the SmartDispatcherController in MonoRail
In a previous article I gave an example of how powerfull the SmartDispatcherController can be, but you can do a lot more with it. You can actually map your Json objects to your objects in the C# code, when you parse it to one of your actions.
1 2 3 4 5 6 | public struct JSONObject { public string Var1; public string Var2; public int[] Var3; } |
There is nothing new here, so moving on.
1 2 3 4 5 6 7 8 9 | new Ajax.Request("/base/testJSON.rails", { method: 'post', parameters: { JSONObject: Object.toJSON( {Var1: 'Hello World', Var2: 'Something else', Var3: [1,2,4]} ) }, onSuccess: function(transport) { alert(transport.responseText); } }); |
If you are new to Prototype, this might look a bit strange, but what it basically does is that it makes an ajax request and parse a Json object as the parameter.
1 2 3 4 | public void testJSON([JSONBinder("JSONObject")] JSONObject myJsonObject) { // Do something } |
The biggest change here, from my previous example, is that instead of using the DataBind attribute, we apply the JSONBinder attribute.
If you want to try this out, then you should reference the Castle.MonoRail.JSONSupport.dll and the Newtonsoft.Json.dll. The last one can be found in the external-dependencies.zip file.