Friday, June 17, 2011

Hide/show column at run time in MVC Telerik Grid with ajax binding

Environment: Telerik Grid for MVC, Razor/Aspx, ajax binding.

I had a search page with some search criteria and on the click of the button, an ajax call is made to get the data. After successful retrieval of data, it is bound to a Telerik Grid.

Issue: Now I had to add a check box to the search criteria, which when checked, should display the results in the grid with this new column (the new column is the one listed by the check box). If unchecked, the column has to hidden. All this with the ajax call backs.

Solution:
1. I tried setting the ViewBag with the an object bearing the checkbox value, so that on the UI, I could check the value of ViewBag's object and turn the column on/off in the Telerik Grid. It didnt work.
2. Tried hinding the table column (td) of this new column, after the successful ajax call back. Didnt work.

Successful:
Finally tried setting the client event of the Telerik grid - "RowDataBound" and in the javascript function "Grid_RowDataBound", hid/displayed the new column in question.


    function Data_GridRowDataBound(e)
    {
        var row = e.row;
 
        //Hide column if the checkbox has not been checked. 
         if($("#Required").attr('checked') == false)
        {
            $('#Data th:eq(8)').hide();
            if($(row).parent().html() != null)
            {
                var cReqdCell = row.cells[8];
                $(cReqdCell).hide();
            }
        }
        else
        {
            $('#Data th:eq(8)').show();
        }
}

In my case, I had to hide the column on initial page load. That I achieved by calling the below javascript method on the jquery's ready method.


        if($("#Required").attr('checked') == false)
        {
            $('#Data colgroup').find('col:eq(8)').hide();
            
            $('#Data th:eq(8)').hide();
            
            $("#Data tbody tr").find("td:eq(8)").each(function(){
                $(this).hide();
            });
        }
$(document).ready(function() { 
  
         HideColumns();
}
Unfortunately I couldn't find the solution on Telerik forums or from their paid support ticket answer.