<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>
Showing posts with label Kendo UI. Show all posts
Showing posts with label Kendo UI. Show all posts
Wednesday, 6 July 2016
How to add and remove filter dynamically from kendo UI Grid
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
Get row and column index on Change 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
Using Javascript
<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>
Tuesday, 18 June 2013
Multi Selection Combobox in Kendo UI
<div> <input id="product" placeholder="Select product..." /> <br /> <input id="hf_product" type="hidden" /> Selected values : <span id="spanproduct"></span> </div> <script type="text/javascript"> $(document).ready(function () { $("#fabric").kendoComboBox({ name: "fabric", dataTextField: "DataText", dataValueField: "DataValue", dataSource: [ { DataText: "Select All", DataValue: "0" }, { DataText: "Cotton", DataValue: "1" }, { DataText: "Polyester", DataValue: "2" }, { DataText: "Cotton/Polyester", DataValue: "3" }, { DataText: "Rib Knit", DataValue: "4" } ], filter: "contains", suggest: true, template: "<input type='checkbox' id='chk_fabric_#=data.DataValue #' onclick='UpdateIdinHF(this);' value='#=data.DataValue #' name='fabric' />" + " " + "${ data.DataText }", close: onClose, change: onChange }); }); var IsItemChecked = false; function UpdateIdinHF(obj) { var id = $(obj).attr('id'); var name = $(obj).attr('name'); var value = parseInt($(obj).attr('value')); var IsChecked = $(obj).is(':checked'); var hf = $("#hf_" + name).get(0); if (value != 0) { UpdateIdInHiddenField(hf, value, IsChecked); var totalchk = $('input[id*="chk_' + name + '"]').not("#chk_" + name + "_0").length; var checkedchk = $('input[id*="chk_' + name + '"]:checked').not("#chk_" + name + "_0").length; if (totalchk == checkedchk) { $("#chk_" + name + "_0").prop("checked", true); } else { $("#chk_" + name + "_0").prop("checked", false); } } else { $('input[id*="chk_' + name + '"]').each(function () { if (parseInt($(this).val()) != 0) { if (IsChecked == true) { $(this).prop("checked", true); UpdateIdInHiddenField(hf, $(this).val(), IsChecked); } else { $(this).prop("checked", false); UpdateIdInHiddenField(hf, $(this).val(), IsChecked); } } }); } IsItemChecked = true; } function onClose(e) { if (IsItemChecked == true) { IsItemChecked = false; e.preventDefault(); } else { ShowSelectedItem(); } } function ShowSelectedItem() { $("#spanfabric").html($("#hf_fabric").val()); } function UpdateIdInHiddenField(hf, id, IsAdd) { if (hf.value == "") { hf.value = ","; } if (IsAdd == true) { if (hf.value.indexOf("," + id + ",") == -1) { hf.value = hf.value + id + ","; } } else if (IsAdd == false) { if (hf.value.indexOf("," + id + ",") >= 0) { hf.value = hf.value.replace("," + id + ",", ","); } } } function onChange(e) { e.sender.value(null); } </script>
If in your page combobox is used more then once then please check below code snippet:
<div> <input id="product" placeholder="Select product..." /> <br /> <input id="hf_product" type="hidden" /> Selected values : <span id="spanproduct"></span> </div> <script type="text/javascript"> $(document).ready(function () { $("#product").kendoComboBox({ name: "product", dataTextField: "DataText", dataValueField: "DataValue", dataSource: [ { DataText: "Select All", DataValue: "0" }, { DataText: "Cotton", DataValue: "1" }, { DataText: "Polyester", DataValue: "2" }, { DataText: "Cotton/Polyester", DataValue: "3" }, { DataText: "Rib Knit", DataValue: "4" } ], filter: "contains", suggest: true, template: "<input type='checkbox' id='chk_product_#=data.DataValue #' onclick='UpdateIdinHF(this);' value='#=data.DataValue #' name='product' />" + " " + "${ data.DataText }", close: onClose, change: onChange }); }); </script>
Friday, 24 May 2013
How to add multiple series dynamically in kendo UI chart
Method1
Below code snippet is only for reference to create Dummy data in MVC.
Controller
Model
Method2
Below code snippet is only for reference to create Dummy data in MVC.
Controller
Model
DOWNLOAD DEMO
<script type="text/javascript"> var dataSource; function GetSelectedDuration() { return $("input:radio[name=Duration]:checked").val(); } function ReBindDataSource() { dataSource = new kendo.data.DataSource({ transport: { read: { url: "http://localhost/Home/GetDummydata", cache: false, data: { Duration: GetSelectedDuration() } } } }); dataSource.fetch(function () { if (dataSource._data.length > 0) { var keys = Object.keys(dataSource._data[0]); ReDrawChart(keys); } }); } function radioClicks() { ReBindDataSource(); } $(document).ready(function () { $("input:radio[name=Duration]").bind("click", radioClicks); $("#mychart").kendoChart({ title: { text: "Dynamic Column" }, legend: { position: "top" }, seriesDefaults: { type: "column" }, valueAxis: { labels: { format: "{0}%" }, line: { visible: true } }, categoryAxis: { field: "Field1", majorGridLines: { visible: false } }, tooltip: { visible: true, format: "{0}%", template: "#= series.field #: #= value #%" } }); ReBindDataSource(); }); // Add series dynamically in chart function ReDrawChart(keys) { var InvalidColumnName = new Array("_events", "uid", "parent", "Field1"); var chart = $("#mychart").data("kendoChart"); var chartOptions = chart.options; var SeriesCount = 0; for (var k = 0; k < keys.length; k++) { var mykey = keys[k]; if ($.inArray(mykey, InvalidColumnName) == -1) { chartOptions.series.push(new Object()); chartOptions.series[SeriesCount].field = mykey; SeriesCount++; } } chart.setDataSource(dataSource); chart.redraw(); } </script> <div> <input checked="checked" name="Duration" type="radio" value="1" />Annully <input name="Duration" type="radio" value="2" />Monthly <input name="Duration" type="radio" value="3" />Weekly <input name="Duration" type="radio" value="4" />Daily </div> <div id="mychart"> </div>
public class HomeController : Controller { [AllowAnonymous] [HttpGet] public JsonResult GetDummydata(int Duration) { List>TestModels> models = GetDummyData(Duration); return Json(models, JsonRequestBehavior.AllowGet); } public List<TestModels> GetDummyData(int Duration) { List<TestModels> models = new List<TestModels>(); switch (Duration) { case (int)DurationType.Annully: TestModels testModel = new TestModels(); testModel.Field1 = "Annully"; testModel.Field2 = 20; testModel.Field3 = 50; testModel.Field4 = 70; models.Add(testModel); break; case (int)DurationType.Monthly: TestModels testModel2 = new TestModels(); testModel2.Field1 = "Monthly"; testModel2.Field2 = 50; testModel2.Field3 = 50; testModel2.Field4 = 50; models.Add(testModel2); break; case (int)DurationType.Weekly: TestModels testModel3 = new TestModels(); testModel3.Field1 = "Weekly"; testModel3.Field2 = 70; testModel3.Field3 = 10; testModel3.Field4 = 90; models.Add(testModel3); break; case (int)DurationType.Daily: TestModels testModel4 = new TestModels(); testModel4.Field1 = "Daily"; testModel4.Field2 = 11; testModel4.Field3 = 111; testModel4.Field4 = 1111; models.Add(testModel4); break; } return models; } }
[Serializable] public class TestModels { public string Field1 { get; set; } public int Field2 { get; set; } public int Field3 { get; set; } public int Field4 { get; set; } }
Method2
<script type="text/javascript"> var dataSource; function radioClicks() { getDataSource(); } function GetSelectedDuration() { return $("input:radio[name=Duration]:checked").val(); } function getDataSource() { dataSource = new kendo.data.DataSource({ transport: { read: { url: "http://localhost:2116/Home/GetDummydata2", cache: false, data: { Duration: GetSelectedDuration() } } } }); dataSource.fetch(function () { GenerateChartFromData(); }); } function GenerateChartFromData() { var chartSeries = []; var keys = Object.keys(dataSource._data[0]); var InvalidColumnName = new Array("_events", "uid", "parent", "Price"); for (var k = 0; k < keys.length; k++) { var mykey = keys[k]; if ($.inArray(mykey, InvalidColumnName) == -1) { chartSeries.push({ xField: "Price", yField: mykey, name: mykey.replace("_", ""), style: "smooth" }); } } var titletxt = "Title text comes here - "; switch (parseInt(GetSelectedDuration())) { case 1: titletxt += "on " + chartSeries[0].name; break; case 2: titletxt += "with multiple series"; break; } $("#chart").kendoChart({ title: { text: titletxt }, legend: { position: "right" }, dataSource: dataSource, seriesDefaults: { type: "scatterLine" }, series: chartSeries, xAxis: { min: 19, max: 46, labels: { format: "{0}" } }, yAxis: { // min: 80, labels: { format: "{0}" }, title: { text: "testTitle" } } }); } $(document).ready(function () { $("input:radio[name=Duration]").bind("click", radioClicks); getDataSource(); }); </script> <div> <input checked="checked" name="Duration" type="radio" value="1" />Single series <input name="Duration" type="radio" value="2" />multiple series </div> <div id="chart"> </div>
public JsonResult GetDummydata2(int Duration) { switch (Duration) { case 1: List<testmodels_1> lst = new List<testmodels_1>(); for (int i = 0; i < 20; i++) { int dtValue = 0; if (i < 10) { dtValue = -478; } else if (i < 12) { dtValue = -78; } else if (i < 14) { dtValue = -28; } else if (i < 16) { dtValue = 22; } else if (i < 18) { dtValue = 72; } else { dtValue = 122; } lst.Add(new TestModels_1() { Price = 20 + i, _07072014 = dtValue }); lst.Add(new TestModels_1() { Price = 20.5M + i, _07072014 = dtValue }); } return Json(lst, JsonRequestBehavior.AllowGet); break; case 2: List<testmodels_2> lst1 = new List<testmodels_2>(); for (int j = 0; j < 20; j++) { int dtValue1 = 0; if (j < 10) { dtValue1 = -478; } else if (j < 12) { dtValue1 = -78; } else if (j < 14) { dtValue1 = -28; } else if (j < 16) { dtValue1 = 22; } else if (j < 18) { dtValue1 = 72; } else { dtValue1 = 122; } lst1.Add(new TestModels_2() { Price = 20 + j, _07072014 = dtValue1, _08072014 = dtValue1 - 20, _08082014 = dtValue1 - 30 }); lst1.Add(new TestModels_2() { Price = 20.5M + j, _07072014 = dtValue1, _08072014 = dtValue1 - 70, _08082014 = dtValue1 - 80 }); } return Json(lst1, JsonRequestBehavior.AllowGet); break; } return Json(new { IsError = true }, JsonRequestBehavior.AllowGet); } public DateTime? GetDateTimeFromString(string strDateTime) { if (!string.IsNullOrEmpty(strDateTime.Trim())) { string pattern = "dd/MM/yyy"; DateTime parsedDate; if (DateTime.TryParseExact(strDateTime.Trim(), pattern, null, System.Globalization.DateTimeStyles.None, out parsedDate)) { return parsedDate; } } return null; }
[Serializable] public class TestModels_1 { public decimal Price { get; set; } public decimal _07072014 { get; set; } } public class TestModels_2 { public decimal Price { get; set; } public decimal _07072014 { get; set; } public decimal _08072014 { get; set; } public decimal _08082014 { get; set; } }
DOWNLOAD DEMO
Thursday, 31 January 2013
Download Files From Grid in Kendo UI
View
Controller
@(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"))
)
)
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
Controller
Model
JS
DOWNLOAD DEMO
@(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"))
)
)
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()); } } }
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; } } }
<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
Subscribe to:
Posts (Atom)
