I created a new object()
in Javascript, put some values into it and passed it to a PageMethod
...
var filters = new object();
filters.Name = $("#tbxName").val();
filters.Age = parseInt($("#tbxAge").val());
PageMethods.getPeople(filters, getPeopleCallback);
... which, in it's signature, receives an dynamic
argument.
[WebMethod]
public static object getPeople(dynamic filters)
{
...
The whole code compiles and run with no problems, except for the server side PageMethod, which understands the dynamic
parameter as a Dictionary
.
When I debug the code to see the definition of the filters
object, it shows me the following type: filters = {System.Collections.Generic.Dictionary<string,object>}
So, the only way deal with it is using it as a Dictionary
...
var name = filters["Name"];
var age = filters["Age"] as int?;
.. But my intention was to use it as a Dynamic object
var name = filters.Name;
var age = filters.Age;
I know that this is not a big deal at all, and there is absolutely no problem for me to access it as a Dictionary (and I also know I can make a DynamicObject
"Proxy" to access the Dictionary like a dynamic object).
I just want to understand this. So:
I was hoping that this could work because I usually define those Filter
Classes on Server Side and create it in Javascript following the same structure, and the PageMethod understands it and convert it correctly when I define that Type as a argument (eg: getPeople(Filters filters)
). So, I was wondering if it could do that also with dynamic objects (saving me time and unnecessary classes).
I appreciate your time and help.
The reason that the page method treats that as a Dictionary is because of how JavaScriptSerializer works internally. Since all JSON objects can be represented as a Dictionary<string, object>
, JSS' first pass is to convert the JSON string into a Dictionary (if no custom converters for the target type are registered) and you end up with that Dictionary as the end result of the conversion for dynamics.
Not easily.
You could experiment with writing your own JavaScriptConverter for dynamic
. This is an example of something in the same ballpark that I wrote a while back: https://gist.github.com/6cfcdfdf2a117fa5e81b
Mine's customizing the serialization behavior instead of deserialization, but you can implement your own code in the Deserialize method to do that.
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