views:

144

answers:

1

Hi, theres not that much information over internet on how to use Trirand JqGrid TreeGrid option with MVC2.

Anybody with an example?

+1  A: 

I did the question, because there's not enough information on the web, or the information is not that complete so you can start working on.

In this example i'm working with user roles.

First the javascript definition:

    var CONTROLLER = '<%= Url.Content("~/") %>Home/';
    jQuery(document).ready(function () {
        $('#jqgTreeGrid').jqGrid({
            //enable TreeGrid
            treeGrid: true,
            //set TreeGrid model
            treeGridModel: 'adjacency',
            //set expand column
            ExpandColumn: 'Name',
            //url from wich data should be requested
            url: CONTROLLER + 'TreeGrid',
            //type of data
            datatype: 'json',
            //url access method type
            mtype: 'POST',
            //columns names
            colNames: ['Name', 'Id', 'Role'],
            //columns model
            colModel: [
                { name: 'Name', index: 'Name', align: 'left' },
                { name: 'Id', index: 'Id', width: 1, hidden: true, key: true },
                { name: 'Role', index: 'Role', width: 1, hidden: true },
            ],                
            //grid width
            width: 'auto',
            //grid height
            height: 'auto'
        });
 });

Now the aspx definition, this is just in case a newbie don't know:

<table id="jqgTreeGrid" class="scroll" cellpadding="0" cellspacing="0"></table>

Controller definition:

[HttpPost]
public ActionResult TreeGrid(FormCollection collection)
{
    int role = -1;
    //Here we get the Roles names this user
    //In my case IsAgent, IsDealer, IsServiceWritter
    //One user can have all roles or any role
    //So the first important thing is get the
    //highest hierarchy role, in this case "IsAgent"
    //And asign to this role a code.
    //So IsAgent = 2, IsDealer = 1, IsServiceWritter = 0

    var rolesArray = (string[])Session["Roles"];
    // We search for the highest hiearchy level and 
    // end up the loop
    foreach (var s in rolesArray)
    {
        if (s ==  ROLE_NAME_AGENT)
        {
            role = (int)RolesEnum.Agent;
            break;
        }
        else
        {
            if (s == ROLE_NAME_DEALER)
            {
                role = (int)RolesEnum.Dealer;
                break;
            }
            else
            {

                if (s == ROLE_NAME_SW)
                {
                    role = (int)RolesEnum.SW;
                    break;
                }
            }
        }
    }
    var children = new List<GetTreeGridValuesResult>();
    int level = 0;
    int parentId = 0;
    // If we found out a level, we enter the if
    if (role != -1)
    {
        // A very important thing to consider is that there
        // are two keys being send from the treegrid component:
        // 1. [nodeid] that is the id of the node we are expanding
        // 2. [n_level] the root is 0, so, if we expand the first child
        // of the root element the level will be 1... also if we expand the second
        // child of the root, level is 1. And so... 
        // If [nodeid] is not found it means that we are not expanding anything,
        // so we are at root level.
        if (collection.AllKeys.Contains("nodeid"))
        {
            //In case we are expanding a level, we retrieve the level we are right now
            //In this example i'll explain the 
            //Tree with id's so you can imagine the way i'm concatenating the id's:
            // In this case we are at Agent level that have 2 dealers and each dealer 3 service writters
            // Agent: 5
            //  |_Dealer1: 5_25
            //      |_SW1: 5_25_1
            //      |_SW2: 5_25_2
            //      |_SW3: 5_25_3
            //  |_Dealer2: 5_26
            //      |_SW4: 5_26_4
            //      |_SW5: 5_26_5
            //      |_SW6: 5_26_6
            // So, if we clic over the SW6: the id will be 5_26_6, his parent will be 5_26
            // Dealer2 Id is 5_26 and his parent will be 5.
            level = int.Parse(collection["n_level"]) + 1;
            //First we split the nodeid with '_' that is our split character.
            var stringSplitted = collection["nodeid"].Split('_');
            //the parent id will be located at the last position of the splitted array.
            parentId = int.Parse(stringSplitted[stringSplitted.Length - 1]);
        }
        //Getting childrens
        var userId = new Guid(Session["UserId"].ToString());
        children = GetTreeGridValues(role, userId, parentId, level);
        //Each children have a name, an id, and a rolename (rolename is just for control)
        //So if we are are root level we send the parameters and we have in return all the children of the root.
    }

    //Preparing result
    var filesData = new
    {
        page = 1,
        total = 1,
        records = children.Count(),
        rows = (from child in children
                select new
                {
                    //table of cells values
                    cell = new[] {
                            child.name, // Correspond to the colmodel NAME in javascript
                            // The next one correspond to the colmodel ID in javascript Id
                            // If we are are the root level the [nodeid] will be empty as i explained above
                            // So the id will be clean. Following the example, just 5
                            // If we are expanding the Agent 5 so, the [nodeid] will not be empty
                            // so we take the Agent id, 5 and concatenate the child id, so 5_25
                            ( collection["nodeid"] == null ? string.Empty : collection["nodeid"] +'_') + child.id, 
                            child.Role, //Correspond to the colmodel ROLE in javascript 
                            //The next attributes are obligatory and defines the behavior of the TreeGrid 
                            //LEVEL: This is the actual level of the child so, root will be 0, that's why i'm adding
                            // one to the level above.
                            level.ToString(),
                            //PARENT ID: If we are at the root [nodeid] will be empty so the parent id is ""
                            // In case of a service writter the parent id is the nodeid, because is the node
                            // we are expanding
                            collection["nodeid"] ?? string.Empty,
                            //IS NOT EXPANDABLE: One thing that was tricky here was that I was using c# true, false
                            //and to make it work it's needed to be strings "true" or "false"
                            // The Child.Role the role name, so i know that if it's a ServiceWriter i'm the last level
                            // so it's not expandable, the optimal way is to get from the database store procedure
                            // if the leaf has children.
                            (child.Role == Enum.GetName(typeof(RolesEnum), RolesEnum.SW) ? "true": "false").ToString(),
                            //IS EXPANDED: I use that is always false,
                            "false"
                          }
                }
               ).ToArray()
    };

    //Returning json data
    return Json(filesData);

}

Hope this tutorial helps somebody :)

BTW: (Remember to vote if the answer was useful)

Sergio
It looks like a nice good commented example! Because you answer on your question yourself it would be better if you mark the answer as "accepted". It helps other. A small remark about your code. In general jqGrid can read boolean data not only as "true" and "false" but also as "1" and "0" or sometime 1 and 0. It produce smaller data which will be send. You can verify this and if it works then improve your example. Your idea to share code examples I find very good!
Oleg