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:

www.byatool.com/users/dostuff

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>
        <div id="divHolder">
        </div>
    </div>
    <div>
        <div id="divFirstPage" class="divLink floatLeft">
            <<
        </div>
        <div id="divPreviousPage" class="divLink floatLeft">
            <
        </div>
        <div id="divNextPage" class="divLink floatLeft">
            >
        </div>
        <div id="divLastPage" class="divLink floatLeft">
            >>
        </div>
    </div>
    <div class="clear"></div>
    <div>
        <div id="divAmountToShowOne" class="divLink floatLeft">
            1
        </div>
        <div id="divAmountToShowFive" class="divLink floatLeft">
            5
        </div>
    </div>
    <div class="clear"></div>

As you can see exactly as advertised.

Ready for the call? It’s waaaaay hard:

        function getGrid(pageNumberIn, amountToShowIn, sortByIn)
        {
            jQuery.getJSON
            (
               //This is the url for the information I need
               "http://www.someurl.com/Forum/IndexJquery/",
               //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
               returned
            );
        }

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.
        jQuery("#divFirstPage").unbind("click");
        jQuery("#divLastPage").unbind("click");
        jQuery("#divNextPage").unbind("click");
        jQuery("#divPreviousPage").unbind("click");
        jQuery("#divAmountToShowOne").unbind("click");
        jQuery("#divAmountToShowFive").unbind("click");

        //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.
        jQuery("#divHolder").children().remove();

        //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);
           mycurrent_cell.appendChild(currentText);
           mycurrent_row.appendChild(mycurrent_cell);

           mytablebody.appendChild(mycurrent_row);
        }

        mytable.appendChild(mytablebody);
        //Don't forget to add the table to the div!!11
        jQuery("#divHolder").append(mytable);
        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:

    jQuery(document).ready
    (
        function setPage()
        {
            getGrid(0, 10, null);
        }
    )

2 thoughts on “ASP.Net MVC, jQuery, JSon, and paging… how’s that for a SOE title?”

    1. Best I can do is host the html file, but right now I have no hosting that MVC works with…

      File is here

      Problem is it doesn’t include the methods from the MVC side as in getting the forum stuff. However, it wouldn’t take much to replicate it.

Comments are closed.