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) {

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  ""

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:


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, jQuery, JSon, and paging… how’s that for a SOE title?

One of the things I’ve come to realize is how easy it easy to do a lot of things with these three buzzwords. In fact, I’m pretty convinced it’s so easy that it’s actually complex and I am a genius. Not buying it? Neither am I.

So for an experiement the other day I decided to try my hand at some sort of dynamic grid using jQuery’s ajax fun and JSon. Just so happens that this works really well with MVC’s REST like makeup. Don’t know what REST is? On a very tool level, it’s using a url and a command to tell the server what to do. So something like:

Could mean either get all users (if using get) or create a user (If using post). And yes that is probably a ridiculously simplistic view so I’d suggest consulting the Wikitruth. In an MVC sense this would be:

Controller: Users
Action: dostuff

Now most likely your Get All Users action isn’t going to the same as your Add A User action, but it was just a stupid example ok?

However, with jQuery what this means is you have a simple url that it can call and get information from, making it incredibly easy to set up a dynamic grid.

So first off, lets say I have a Forum controller with an action of IndexJquery… yeah I know cheesy name, but it gets the job done. Basically the method IndexJquery would have to take in a page number and optionally (And for this example) how many items to show along with a sort. With that it should return a JSon “object” that will be in this example holds first page, last page, next page, previous page, sortBy, and some kind of list of stuff. (For the two people actually reading this, comment if you want the c# code. It’s really just basic MVC stuff.)

The markup for this is pretty simple. I have a div to hold the grid, four directional divs that work as buttons (First, Previous, Next, Last), and two div “butons” for how many items to show.

        <div id="divHolder">
        <div id="divFirstPage" class="divLink floatLeft">
        <div id="divPreviousPage" class="divLink floatLeft">
        <div id="divNextPage" class="divLink floatLeft">
        <div id="divLastPage" class="divLink floatLeft">
    <div class="clear"></div>
        <div id="divAmountToShowOne" class="divLink floatLeft">
        <div id="divAmountToShowFive" class="divLink floatLeft">
    <div class="clear"></div>

As you can see exactly as advertised.

Ready for the call? It’s waaaaay hard:

        function getGrid(pageNumberIn, amountToShowIn, sortByIn)
               //This is the url for the information I need
               //this is the construction of the "object" to send... really this just
               //means that I have a method somewhere looking for pageNumber,
               //amountToShow, and sortBy
                   pageNumber: pageNumberIn,
                   amountToShow: amountToShowIn,
                   sortBy: sortByIn
               //This is the method to call once this ajax transaction has completed...
               //transaction may not be the best word.  Basically it has to be a method
               //that takes in the result from the getJSon call

Next would be the script to actually create the grid. Looks verbose, but most likely thats because I didn’t refactor much.

    function returned(jsonObject)
        //Have to remove all the previous click event handlers since because
        //this is all client side, there's no "refresh" and therefore the object
        //is still in memory.  So even though I might call the method to get the
        //information, the "objects" are still in memory.

        //Ok so now that the event is not being listened to, set up the listeners
        //The idea is to call that getGrid method and pass in the values straight
        //off the previously returned json object.  Using jQuery's easy .click method
        //makes this so simple.
        jQuery("#divFirstPage").click(function() { getGrid(jsonObject.FirstPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divPreviousPage").click(function() { getGrid(jsonObject.PreviousPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divNextPage").click(function() { getGrid(jsonObject.NextPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divLastPage").click(function() { getGrid(jsonObject.LastPage, jsonObject.AmountToShow, jsonObject.SortBy); })
        jQuery("#divAmountToShowOne").click(function() { getGrid(0, 1, jsonObject.SortBy); })
        jQuery("#divAmountToShowFive").click(function() { getGrid(0, 5, jsonObject.SortBy); })

        //Again since this is client side, the divHolder "object" still is holding
        //the previous results.  These have to be cleared.

        //Create the table and loop through the list.
        var mytable = document.createElement("table");
        var mytablebody = document.createElement("tbody");

        for (loopCounter = 0; loopCounter < jsonObject.ListForViewing.length; loopCounter++)
           var currentItem = something.ListForViewing[loopCounter];
           var mycurrent_row = document.createElement("tr");

           var mycurrent_cell = document.createElement("td");
           var currentText = document.createTextNode(currentItem.ForumName);


        //Don't forget to add the table to the div!!11
        return false;

And boom. So easy even a ca… tool can do it. Now if you want this grid to come preloaded, it’s pretty easy:

        function setPage()
            getGrid(0, 10, null);