12
votes

How to set columns dynamically in Kendo template for kendo grid.In my kendo grid,columns are subject to change dynamically based on user preference.How to dynamically create Kendo Template?I am using Kendo JavaScript,I can switch to Kendo MVC if same thing i can achieve there.Is there any other approach to achieve this?

<script id="rowTemplate" type="text/x-kendo-template">
        <tr class="k-master-row">

            <td>

                    <div>#=column1#</div>

            </td>
            <td><span class="mydesign" title="column2#"</span></td>
            <td>#column3#</td>
            <td>#=column4#</td>

        </tr>
    </script>

Edit : In Kendo grid, we are dynamically setting the columns. Now issue is how do we set the dynamic width for content table and the header table. If it exceeds the max width how do we enable the horizontal scroll bar. Is there any approach to achieve this?

3
Maybe load all initially and then hide the ones the user has indicatedMario Garcia
can you tell me more of what changes do you want in your column, do you want to change the value in column or some html property of column or what?Rajdeep
i want different columns..columns value can change..lets say I have column a,b,c now I should be able to add new coulmn "d" or remove existing column "c"F11
ok, you want to add column in each row of your grid ? you have multiple rows ?Rajdeep
yes requirement is Columns should be shown based on user preferenceF11

3 Answers

3
votes

I'm not using kendo for MVC but I can still explain how to do this using regular kendo functions.

Basically, you can create a new kendo template instance by passing an html string to kendo.template. Then you can assign the new template instance to the grid's rowTemplate (or altRowTemplate) then call dataSource.read() to force a grid refresh.

You can generate your own html string or update an existing template in your page then use the jquery's html() to convert it into a string.

Ex:

var htmlTemplate = '';
if (userPreferences.likeRed) {
    htmlTemplate ='<tr class="k-master-row"><td style="background-color:red">#column1#</td></tr>'
} else {
    htmlTemplate ='<tr class="k-master-row"><td style="background-color:green">#column1#</td></tr>'
}

$("#grid").data("kendoGrid").rowTemplate = kendo.template(htmlTemplate);
$("#grid").data("kendoGrid").dataSource.read();
0
votes

In order to format Kendo Grid column value with conditionally chosen action you can use one of the suitable examples below. For more information: How Do I Have Conditional Logic in a Column Client Template?

Here are some of the usage samples below. You can easily generate different templates with the help of this approach.

UI for Javascript:

{
    field: "EmployeeName", type: "string", width: "55px", title: "Employee Name", 
        template: "#= GetEditTemplate(data) #"
}

UI for MVC:

...
columns.Bound(t => t.EmployeeName)
       .Title("Status Name")
       .Template(@<text></text>)
       .ClientTemplate("#= GetEditTemplate(data)#")
       .Width("55px");
...


Example I: In this example, Model is passed to the Javascript method by using "data" property and the model property is used in the "if" condition.

<script>
//Change the color of the cell value according to the given condition
function GetEditTemplate(data) {
    var html;    
    if (data.StatusID == 1) {
        html = kendo.format(
        //"<a class=\"k-button\" href='" + '@Url.Action("Edit1", "Controller")' + "/{0}" + " '>Edit</a>  ",
        "<span class='text-success'>" +
        data.EmployeeName
        + "</span>"
        );
    }
    else {
        html = kendo.format(
        //"<a class=\"k-button\" href='" + '@Url.Action("Edit2", "Controller")' + "/{0}" + " '>Edit</a>  ",
        "<span class='text-danger'>Cancel</span>"
        );
    }
    return html;
}
</script>


Example II:

<script>
function Getvalue(value) {
    // console.log(value);
    if (value && value != null && value.indexOf("A") == 0)
        return "<b style='color:red'>" + value + "</b>";
    else
        return "";
}

$(document).ready(function () {  
    $("#grid").kendoGrid({
        dataSource: localDataSource,
        columns: [
            {
                field: "FirstName",
                title: "First Name", template: '#=Getvalue(FirstName)#'
            }
        ],
    });
});
</script>

Hope this helps...

-1
votes

This will work in ASP.NET MVC/Razor, if you prepare a collection of the dynamic columns definitions in advance, then put them in the view model for the cshtml. Then loop through the collection and insert the field name that will match the datasource, header title, desired width, etc...

     $("#grid-quick").kendoGrid({
        pageable: {
            pageSizes: [10, 20, 50, 100]
        },
        sortable: { mode: "multiple" },
        columns: [
            @{
                foreach (var col in Model.Columns)
                {
                    @:{ field: "@col.Name.Replace(".","_")", width: "@col.Width" + "px" },
                }
            }
        ],
        filterable: false,
        dataSource: {
            serverPaging: true,
            serverSorting: true,
            pageSize: 20,
            type: 'aspnetmvc-ajax',
            schema: {
                data: "Data",
                total: "Total",
                model: {
                    fields: {
                        @{
                            foreach (var col in Model.Columns)
                            {
                                @: "@col.Name.Replace(".","_")" : { type: "string" },
                            }
                        }
                    }
                }
            },
            transport: {
                read: {
                    url: oVariables.baseURL + "Query/DynamicResults",
                    dataType: "json",
                    type: "post"
                }
            }
        }
    });