Showing posts with label Kendo Grid. Show all posts
Showing posts with label Kendo Grid. Show all posts

Wednesday, 6 July 2016

How to add and remove filter dynamically from kendo UI Grid


<script>
    $(document).ready(function () {

        var products = [{
            ProductID: 1,
            ProductName: "Chai",
            SupplierID: 1,
            CategoryID: 1,
            QuantityPerUnit: "10 boxes x 20 bags",
            UnitPrice: 18.0000,
            UnitsInStock: 39,
            UnitsOnOrder: 0,
            ReorderLevel: 10,
            Discontinued: false,
            Category: {
                CategoryID: 1,
                CategoryName: "Beverages",
                Description: "Soft drinks, coffees, teas, beers, and ales"
            }
        }, {
            ProductID: 2,
            ProductName: "Chang",
            SupplierID: 1,
            CategoryID: 1,
            QuantityPerUnit: "24 - 12 oz bottles",
            UnitPrice: 19.0000,
            UnitsInStock: 17,
            UnitsOnOrder: 40,
            ReorderLevel: 25,
            Discontinued: false,
            Category: {
                CategoryID: 1,
                CategoryName: "Beverages",
                Description: "Soft drinks, coffees, teas, beers, and ales"
            }
        }, {
            ProductID: 3,
            ProductName: "Aniseed Syrup",
            SupplierID: 1,
            CategoryID: 2,
            QuantityPerUnit: "12 - 550 ml bottles",
            UnitPrice: 10.0000,
            UnitsInStock: 13,
            UnitsOnOrder: 70,
            ReorderLevel: 25,
            Discontinued: false,
            Category: {
                CategoryID: 2,
                CategoryName: "Condiments",
                Description: "Sweet and savory sauces, relishes, spreads, and seasonings"
            }
        }, {
            ProductID: 4,
            ProductName: "Chef Anton's Cajun Seasoning",
            SupplierID: 2,
            CategoryID: 2,
            QuantityPerUnit: "48 - 6 oz jars",
            UnitPrice: 22.0000,
            UnitsInStock: 53,
            UnitsOnOrder: 0,
            ReorderLevel: 0,
            Discontinued: false,
            Category: {
                CategoryID: 2,
                CategoryName: "Condiments",
                Description: "Sweet and savory sauces, relishes, spreads, and seasonings"
            }
        }, {
            ProductID: 5,
            ProductName: "Chef Anton's Gumbo Mix",
            SupplierID: 2,
            CategoryID: 2,
            QuantityPerUnit: "36 boxes",
            UnitPrice: 21.3500,
            UnitsInStock: 0,
            UnitsOnOrder: 0,
            ReorderLevel: 0,
            Discontinued: true,
            Category: {
                CategoryID: 2,
                CategoryName: "Condiments",
                Description: "Sweet and savory sauces, relishes, spreads, and seasonings"
            }
        }];

        $("#grid").kendoGrid({
            dataSource: {
                data: products,
                schema: {
                    model: {
                        id: "ProductID",
                        fields: {
                            ProductID: { type: 'number' },
                            UnitsInStock: { type: 'number' },
                            ProductName: { type: 'string' },
                            QuantityPerUnit: { type: 'string' },
                            UnitPrice: { type: 'number' },
                        }
                    }
                },
            },
            filterable: {
                mode: "row"
            },
            resizable: true,
            columns: [
                { field: "ProductName" },
                { field: "UnitsInStock", title: "UnitsInStock" },
                { field: "QuantityPerUnit", title: "QuantityPerUnit" },
                { field: "UnitPrice", title: "UnitPrice" },
            ]
        });



    });

    function AddFilterinGrid() {
        var grid = $("#grid").data("kendoGrid");
        addOrRemoveFilter(grid, "ProductName", "eq", "Chai");
    }

    function RemoveFilterinGrid() {
        var grid = $("#grid").data("kendoGrid");
        addOrRemoveFilter(grid, "ProductName", "eq", "");
    }

    function addOrRemoveFilter(grid, field, operator, value) {

        var newFilter = { field: field, operator: operator, value: value };
        var dataSource = grid.dataSource;
        var filters = null;
        if (dataSource.filter() != null) {
            filters = dataSource.filter().filters;
        }

        if (value && value.length > 0) {
            //Add filter
            if (filters == null) {
                filters = [newFilter];
            }
            else {
                var isNew = true;
                var index = 0;
                for (index = 0; index < filters.length; index++) {
                    if (filters[index].field == field) {
                        isNew = false;
                        break;
                    }
                }
                if (isNew) {
                    filters.push(newFilter);
                }
                else {
                    filters[index] = newFilter;
                }
            }
        }
        else {
            //Remove filter 
            var removeIndex = -1;
            for (var x = 0; x < filters.length; x++) {
                var temp = filters[x];
                if (temp.field == field) {
                    removeIndex = x;
                    break;
                }
            }
            if (removeIndex != -1)
                filters.splice(removeIndex, 1);
        }
        dataSource.filter(filters);
    }
</script>

Thursday, 1 October 2015

Get row and column index on change event or on click event on Kendo-UI Grid

Get row and column index on click event

function onDataBound(e) {
    var grid = $("#Grid").data("kendoGrid");
    $(grid.tbody).on("click", "td", function (e) {
        var row = $(this).closest("tr");
        var rowIdx = $("tr", grid.tbody).index(row);
        var colIdx = $("td", row).index(this);
        alert(rowIdx + '-' + colIdx);
    });
}

$(document).ready(function () {
    $("#Grid").kendoGrid({
        dataSource: {
            type: "odata",
            transport: {
                read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
                dataType: "jsonp"
            },
            schema: {
                model: {
                    fields: {
                        OrderID: { type: "number" },
                        Freight: { type: "number" },
                        ShipName: { type: "string" },
                        OrderDate: { type: "date" },
                        ShipCity: { type: "string" }
                    }
                }
            },
            pageSize: 10,
            serverPaging: true,
            serverFiltering: true,
            serverSorting: true
        },
        dataBound: onDataBound,
        filterable: true,
        sortable: true,
        pageable: true,
        columns: [{
            field: "OrderID",
            filterable: false
        },
                        "Freight",
                        {
                            field: "OrderDate",
                            title: "Order Date",
                            width: 120,
                            format: "{0:MM/dd/yyyy}"
                        }, {
                            field: "ShipName",
                            title: "Ship Name",
                            width: 260
                        }, {
                            field: "ShipCity",
                            title: "Ship City",
                            width: 150
                        }
                    ]
    });
});
<div id="Grid">
</div>

Get row and column index on Change event

<body>
    <script>

        function onChange(arg) {
            var grid = $("#Grid").data("kendoGrid");
            var row = this.select().closest("tr");
            var rowIdx = $("tr", grid.tbody).index(row);
            var colIdx = this.select().index();
            alert(rowIdx + '-' + colIdx);
        }

        $(document).ready(function () {
            $("#Grid").kendoGrid({
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
                        dataType: "jsonp"
                    },
                    schema: {
                        model: {
                            fields: {
                                OrderID: { type: "number" },
                                Freight: { type: "number" },
                                ShipName: { type: "string" },
                                OrderDate: { type: "date" },
                                ShipCity: { type: "string" }
                            }
                        }
                    },
                    pageSize: 10,
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true
                },

                selectable: "multiple cell",
                change: onChange,
                filterable: true,
                sortable: true,
                pageable: true,
                columns: [{
                    field: "OrderID",
                    filterable: false
                },
                                "Freight",
                                {
                                    field: "OrderDate",
                                    title: "Order Date",
                                    width: 120,
                                    format: "{0:MM/dd/yyyy}"
                                }, {
                                    field: "ShipName",
                                    title: "Ship Name",
                                    width: 260
                                }, {
                                    field: "ShipCity",
                                    title: "Ship City",
                                    width: 150
                                }
                ]
            });
        });

    </script>
    <div id="Grid">
</div>
</body>

Thursday, 29 August 2013

How to add serial number column in kendo ui grid

Using MVC
<script type="text/javascript">
    var rowNumber = 0;

    function resetRowNumber(e) {
        rowNumber = 0;
    }

    function renderNumber(data) {
        return ++rowNumber;
    }

    function renderRecordNumber(data) {
        var page = parseInt($("#Grid").data("kendoGrid").dataSource.page()) - 1;
        var pagesize = $("#Grid").data("kendoGrid").dataSource.pageSize();
        return parseInt(rowNumber + (parseInt(page) * parseInt(pagesize)));
    }

</script>

@(Html.Kendo().Grid<MvcApplication1.Models.TestModels>() 
.Name("Grid") 
.Columns(columns => { 
             columns.Bound(p => p.ID); 
             columns.Bound(p => p.Name); 
             columns.Template(t => { }).Title("Row No").ClientTemplate( "#= renderNumber(data) #" ); 
             columns.Template(t => { }).Title("Record No").ClientTemplate( "#= renderRecordNumber(data) #" ); 
         }) 
.Pageable(x => x.PageSizes(new int[] { 10, 20, 30, 50 }).Refresh(true)) 
.Sortable() 
.Filterable() 
.DataSource(dataSource => dataSource.Ajax()
            .Read(read => read.Action("Grid_Read", "Home")) 
            ) 
 .Events(ev => ev.DataBound("resetRowNumber")) 
) 

Using Javascript
<div id="Grid">
</div>
<script>
    
    var rowNumber = 0;

    function resetRowNumber(e) {
        rowNumber = 0;
    }

    function renderNumber(data) {
        return ++rowNumber;
    }

    function renderRecordNumber(data) {
        var page = parseInt($("#Grid").data("kendoGrid").dataSource.page()) - 1;
        var pagesize = $("#Grid").data("kendoGrid").dataSource.pageSize();
        return parseInt(rowNumber + (parseInt(page) * parseInt(pagesize)));
    }

    $(document).ready(function () {

        $("#Grid").kendoGrid({
            dataSource: {
                type: "odata",
                transport: {
                    read: "http://demos.kendoui.com/service/Northwind.svc/Orders",
                    dataType: "jsonp"
                },
                pageSize: 10
            },
            pageable: {
                refresh: true,
                pageSizes: true
            },
            dataBound: resetRowNumber,
            columns: [
                                { field: "OrderID", title: "Order ID", width: 60 },
                                { field: "CustomerID", title: "Customer ID", width: 90 },
                                { title: "Row No", width: 90, template: "#= renderNumber(data) #" },
                                { title: "Record No", width: 90, template: "#= renderRecordNumber(data) #" }
                            ]
        });

    });
</script>

Thursday, 31 January 2013

Download Files From Grid in Kendo UI

View
@(Html.Kendo().Grid<MvcApplication1.Models.TestModels>()
    .Name("Grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.ID).Groupable(false);
        columns.Bound(p => p.Name);
        columns.Template(@).ClientTemplate("Download file").Title("Download1");
        columns.Template(@).ClientTemplate("" + Html.ActionLink("Download me", "DocumentDownload2", "Home", new { id = "#=ID#" }, null) + "").Title("Download2");

    })

     .DataSource(dataSource => dataSource
          .Ajax()
          .Read(read => read.Action("Grid_Read", "Home"))
     )
)
Controller
public ActionResult Grid_Read([DataSourceRequest] DataSourceRequest request)
{
    List<TestModels> models = new List<TestModels>();

    for (int i = 1; i < 6; i++)
    {
        TestModels model = new TestModels();
        model.ID = i;
        model.Name = "Name" + i;
        models.Add(model);
    }

    return Json(models.ToDataSourceResult(request));
}


public ActionResult DocumentDownload1()
{
    string contentType = "application/xlsx";
    string filePath = Server.MapPath("~/Files/YourFileName.xlsx");
    return File(filePath, contentType, "YourFileName.xlsx");
}

public ActionResult DocumentDownload2(int id)
{
    string contentType = "application/xlsx";
    string filePath = Server.MapPath("~/Files/YourFileName.xlsx");
    return File(filePath, contentType, "YourFileName_" + id.ToString() + ".xlsx");
}

Wednesday, 16 January 2013

Set column editable mode based on another column value changes in kendo UI

View
@(Html.Kendo().Grid<MvcApplication1.Models.TestModels>()
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ID);
            columns.Bound(p => p.Name);
            columns.Bound(p => p.IsActive);
            columns.ForeignKey(p => p.FID, (System.Collections.IEnumerable)ViewData["TestList"], "Value", "Text");

        })
        .ToolBar(toolBar => toolBar.Save())
        .Editable(editable => editable.Mode(GridEditMode.InCell))
        .Pageable()
        .Sortable()
        .Scrollable()
        .Filterable()
        .Events(e => e.Edit("onGridEdit"))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Batch(true)
            .ServerOperation(false)
            .Events(events => events.Error("errorHandler"))
            .Model(model =>
            {
                model.Id(p => p.ID);
                model.Field(p => p.ID).Editable(false);
            })
        .Read(read => read.Action("ForeignKeyColumn_Read", "Home"))
        .Update(update => update.Action("ForeignKeyColumn_Update", "Home"))
        )
    )
Controller
namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {

            List<SelectListItem> items = new List<SelectListItem>();

            for (int i = 1; i < 6; i++)
            {
                SelectListItem item = new SelectListItem();
                item.Text = "text" + i.ToString();
                item.Value = i.ToString();
                items.Add(item);
            }

            ViewData["TestList"] = items;

            return View();
        }

        public ActionResult ForeignKeyColumn_Read([DataSourceRequest] DataSourceRequest request)
        {
            List<TestModels> models = new List<TestModels>();

            for (int i = 1; i < 6; i++)
            {
                TestModels model = new TestModels();
                model.ID = i;
                model.Name = "Name" + i;
                
                if (i % 2 == 0)
                {
                    model.IsActive = true;
                    model.FID = i;
                }

                models.Add(model);
            }

            return Json(models.ToDataSourceResult(request));
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ForeignKeyColumn_Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable<TestModels> tests)
        {
            if (tests != null && ModelState.IsValid)
            {
                // Save/Update logic comes here
            }

            return Json(ModelState.ToDataSourceResult());
        }
    }
} 
Model
namespace MvcApplication1.Models
{
    public class TestModels
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsActive { get; set; }
        public int FID { get; set; }
    }
}
JS
<script type="text/javascript">

    function errorHandler(e) {
        if (e.errors) {
            var message = "Errors:\n";
            $.each(e.errors, function (key, value) {
                if ('errors' in value) {
                    $.each(value.errors, function () {
                        message += this + "\n";
                    });
                }
            });
            alert(message);
        }
    }

    function onGridEdit(arg) {
        if (arg.container.find("input[name=IsActive]").length > 0) {
            arg.container.find("input[name=IsActive]").click(function () {
                if ($(this).is(":checked") == false) {
                    arg.container.next().html("");
                    arg.model.FID = "0";
                }
                else {
                    arg.model.IsActive = true;
                    $("#Grid").data("kendoGrid").closeCell(arg.container);
                    $("#Grid").data("kendoGrid").editCell(arg.container.next());
                }
            });
        }
        if (arg.container.find("input[name=FID]").length > 0) {
            if (arg.model.IsActive == false) {
                $("#Grid").data("kendoGrid").closeCell(arg.container)
            }
        }
    }
</script>

DOWNLOAD DEMO