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.

ASP.Net MVC 2/C# 4… Dynamic Model and Should You Use It?

So there’s a new sheriff in town and its name is dynamic. Actually, its not really that new and that’s a horribly misused cliche. My lack of literary genius aside, I’ve been looking for a reason to use dynamic. Then it came to me: Models. Now the only reason why I started down that path was the use of Python where pretty much anything is dynamic. In using python, I got used to not embracing the rigidity of classes for models and adopted a more “Oh what the f–k” attitude. Back in the .net world though, I was using typed views. Then I readopted the “Oh what the f–k” attitude and applied it to .net mvc.

Here’s an example:

    [RequiresAuthentication]
    public ActionResult ShowBasicInfo()
    {
      IState currentState = ObjectFactory.Create();
      dynamic returnModel = new ExpandoObject();

      returnModel.UserName = currentState.CurrentUser.UserName;

      return View(AccountActions.ShowBasicInfo, returnModel);
    }

As you can see, I created a dynamic class and just added a property to it. Now on the view side:

...
@model dynamic
...
          <label id="showBasicInfoEmail" name="showBasicInfoEmail">@Model.UserName</label>
...

So if that’s all you’re here for, well there you go. Now get out.

Ok so the real point to this post was actually the “should I?” Now with .Net, you really have to adopt a “should I?” attitude on anything that is new otherwise it might come back to bite you in the a–. (Update panels anyone?) Just using something because it looks easier is NOT a reason to do so.

The reason why I originally gravitated toward typed views was I didn’t like all the magic sting junk that came with the View dictionary, or whatever the hell it was called. (I’m too lazy to look it up) Typed views gave a sort of concrete nature much like an interface does to a class. You knew exactly WHAT the view could show based on the model. This is good I still think in an environment where you don’t trust people to code correctly or when a person needs an easy place to look up what the incoming model contains. After all, on the second point I mean, its a lot easier to look at a class to find EXACTLY what the model has than looking at a controller action code. Simple for reference.

With that being said, getting stuck in model hell can happen. After all for every action there is an equal and… wait… there is a model. Yeah you can reuse models to cut that down, but its not too hard to imagine it becoming a model infested nightmare. Sometimes you just have to take the good and the bad, but sometimes you’re able to trust people and just go with what is easier.

Why trust? With Python and it overall dynamic nature, it was easy to see that such a tool put in the wrong hands could be a disaster. Anyone who has worked with JavaScript will know this pain. Python is just a fancy way to annihilate your foot, so the concept of allowing dynamic models only made me shiver like a prostitute on Christmas. Sorry, that wasn’t appropriate. I meant a prostitute on a non religious holiday like Thanksgiving or the Chinese New Year. (Sorry non Christian readers)

On the other hand, when in a small group where you have less time and more to do, it could be used as a compromise as it doesn’t use the hated magic string dictionary thing approach, but still had a class like feel. And on top of that, if you wish to create models later, it would be extremely easy to swap the @model dynamic with whatever class type you need. So in that way, I can almost stop my non stop convulsing that is a natural reaction to doing something I deem bad.

Answer is: I don’t f–king know right now, but I’m going to fly with it and see how I like it.

Side note: One drawback of the dynamic route is the lack of intellisense. That could be a deal killer for some.