ASP.Net MVC2, Dynamic Models, Json, and Javascript

Ok so one thing I fell into while using the dynamic keyword as a model, was an issue with the dynamic model being parsed into json and then back again into javasript using jQuery. Silly me, I thought that the dynamic model would represent itself like any other object, but it turns out the dynamic object is actually a dictionary with a key value pair. Now I’m not going to harp on that since I think that’s kind of how Python does it (And javascript for that matter), but I did want this:

function doSomething(result) {
  if(result.Success){
    alert(result.Value.UserName);
  }
}

Where the result value was:

...  //Other junk
dynamic returnModel = new ExpandoObject();
returnModel.UserName = _state.CurrentUser.UserName;
result.Value = returnModel;
...  //set the data on a jSonResult to that result above and return.

But what I got for Value was a dictionary:

  result.Value[0].Key  "UserName"
  result.Value[0].Value  "test@test.com"

As you can guess, using the javascript from above won’t work. However, there is a way to run the above javascript.

    var convertedValue = new Object;

    for(var i = 0; i < result.Value.length; i++){
      convertedValue [result.Value[i].Key] = result.Value[i].Value;
    }

You see with javascript, like the dynamic object, the objects not only respond to a direct assignment like a property, but can also be manipulated like a dictionary. Where does that code above get me? Well simple, I can now do:

  alert(convertedValue.UserName);

Yeah its not perfect and I have to think there will be some way for a better json translation, but for now this is gold.