Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receiving dynamic object in PageMethod from Javascript

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:

  1. Why the PageMethod understands it as a Dictionary?
  2. Is there a way to make this work as a Dynamic object (except for the "Proxy" approach)?

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.

like image 566
everton Avatar asked Nov 05 '22 08:11

everton


1 Answers

  1. 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.

  2. 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.

like image 53
Dave Ward Avatar answered Nov 09 '22 15:11

Dave Ward