concardation of chart in kendoui mvc - kendo-ui-mvc

I am using two chart in two different place and both the chart shown sam data and using different controller and model.
here is the code:
#(Html.Kendo().Chart<AccountChartModel>()
.Name("chart")
.Title("Sales by Month")
.Legend(legend => legend
.Position(ChartLegendPosition.Bottom)
)
.ChartArea(chartArea => chartArea
.Background("transparent")
)
.SeriesDefaults(seriesDefaults =>
seriesDefaults.Line().Style(ChartLineStyle.Smooth)
)
.Series(series =>
{
series.Line(Model.ValueAxis).Name("Sales");
//series.Line(new double[] { 18495.68, 5748.87, 30000.99, 15005.78, 48520, 29789.14, 9874 }).Name("Sales");
//series.Line(new double[] { 4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247, -7.832, 4.3, 4.3 }).Name("Russian Federation");
//series.Line(new double[] { -0.253, 0.362, -3.519, 1.799, 2.252, 3.343, 0.843, 2.877, -5.416, 5.590 }).Name("Haiti");
})
.CategoryAxis(axis => axis.Categories(Model.CategoryAxis)
//.Categories("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul")
.MajorGridLines(lines => lines.Visible(false))
)
.ValueAxis(axis => axis
.Numeric()/*.Labels(labels => labels.Format("{0}%"))*/
.Line(line => line.Visible(false))
//.AxisCrossingValue(-10)
)
.Tooltip(tooltip => tooltip
.Visible(true)
.Template("#= series.name #: #= value # $")
)
//.HtmlAttributes(new { style="height:600px"})
)
but when first chart is open in different page second chart not opening.Can anyone tell me what should i do?

Related

Pass values of kendo grid to popup window

I have implemented a kendo grid and context menu in my MVC5 page. I open a window on click of the Update Status menu. I need to retrieve the requestid and couple of other fields from the selected row in the pop up window. I would also need to show a drop down control with values. Whats the best way of doing it
Grid
div class="requestgrid" id="requestGrid">
#(Html.Kendo().Grid<CC.GRP.MCRequest.ViewModels.RequestViewModel>()
.Name("GridRequest")
.Columns(columns => {
columns.Bound(o => o.RequestID).Width("100px");
columns.Bound(o => o.CountryCode).Width("100px");
columns.Bound(o => o.SalesOffice).Width("100px");
columns.Bound(o => o.CustomerNumber).Width("120px");
columns.Bound(o => o.ProjectName).Width("120px");
columns.Bound(o => o.ProjectContent).Width("120px");
columns.Bound(o => o.ContractStartDate).Width("140px");
columns.Bound(o => o.Priority).Width("120px");
columns.Bound(o => o.NameOfResponsiblePerson).Width("170px");
columns.Bound(o => o.Status).Width("100px");
columns.Bound(o => o.CreatedBy).Width("110px");
columns.Bound(o => o.CreatedDate).Width("110px");
columns.Bound(o => o.ModifiedBy).Width("110px");
})
//.ToolBar(toolbar => toolbar.Create())
//.Editable(editable => editable.Mode(GridEditMode.PopUp))
.Pageable()
.Sortable()
.Filterable()
.Scrollable()
.Groupable()
.Selectable(selectable => selectable
.Mode(GridSelectionMode.Single)
.Type(GridSelectionType.Row))
.Events(events => events
.Change("onChange")
)
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(t => t.RequestID))
//.Create(update => update.Action("Team_Create", "Admin"))
.Read(read => read.Action("Requests_Read", "Request"))
//.Update(update => update.Action("Team_Update", "Admin"))
)
)
Context Menu
#(Html.Kendo().ContextMenu()
.Name("RequestMenu")
.Target("#GridRequest")
.Filter("tr")
.Orientation(ContextMenuOrientation.Vertical)
.Animation(animation =>
{
animation.Open(open =>
{
open.Fade(FadeDirection.In);
open.Duration(500);
});
})
.Items(items =>
{
items.Add()
.Text("Edit");
items.Add()
.Text("Update Status");
})
.Events(e =>
{
e.Select("onSelect");
})
)
Javascript
function onSelect(e) {
var grid = $("#GridTeam").data("kendoGrid");
var requestId;
switch ($(e.item).children(".k-link").text()) {
case "Edit":
var grid = $("#GridRequest").data("kendoGrid");
var column = grid.columns[0];
var selectedBackup = grid.dataItem(grid.select());
requestId = selectedBackup.id;
window.location.href = '#Url.Action("EditRequest", "Request", new { id = "_id_", status="Edit" })'.replace('_id_', requestId);
break;
case "Update Status":
//alert("Work in progress");
//$('#window1').data('kendoWindow').center().open();
var myWindow = $("#window");
//e.preventDefault();
//var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//kendo.bind($("#window"), dataItem);
myWindow.kendoWindow({
width: "400px",
height: "180px",
title: "Update Request Status",
modal: true,
visible: false,
actions: ["Minimize", "Maximize", "Close"],
}).data("kendoWindow");
myWindow.data("kendoWindow").center().open();
}
You're doing it almost right, only by two details:
If you bind the contextMenu's target to the grid's container, you'll never be sure which row user did clicked. I suggest you to bind to your grid's rows(TR) instead, e.g. #GridRequest tbody tr;
I'm afraid e.currentTarget doesn't exists or returns undefined in that context. You should use e.target which will point to the clicked row if you did what I suggested above. Then you could get your dataItem as follows:
grid.dataItem(e.target);
Check out this demo with my suggestions working.

Kendo grid error missing when scrolling

I have simple kendo grid with scrolling. It shows 20 items at the beginning and when scrolling it gets dynamically more data and add to the grid.
Normally when getting data for first page when grid is loading, when dataService throws exception like this:
return new HttpStatusCodeResult((int)HttpStatusCode.ServiceUnavailable, this.T("System Error - retrying.").Text);
and my js method binded in configuration
Events(events => events.Error("acc.mp.gridErrorDialog"))
catch it and display proper message.
The problem is with next page, when grid is getting more data.
I have seen that is happend when I toucht the scroll and scroll like 3 rows (even thought page size is 20), grid is trying to get data to the buffer to show them when I scroll 20 items.
But when error happens in this operation, the same like in first query, Kendo grid is not showing it immediately (becuse I didn't scrool yet 20 rows only it keeps its in his buffer) and nothing happen, and when I scroll to 20 rows spinner shows and all frezes. Method acc.mp.gridErrorDialog is not fired.
Grid initialization:
public static GridBuilder<T> InitializeGrid<T>(this GridBuilder<T> gridBuilder, string gridName, string dataBindAction, string controllerName, object routeValues) where T : class
{
if (gridBuilder == null)
{
throw new ArgumentNullException("gridBuilder");
}
return
gridBuilder
.Name(gridName)
.TableHtmlAttributes(new { Class = "styled", cellpadding = "0", border = "0", margin = "0" })
.HtmlAttributes(new { Class = "dynamicGridHeight" })
.AutoBind(false)
.DataSource(
dataSource =>
dataSource.Ajax()
.PageSize(ModelPortfolioConfigurationManager.GridPageSize)
.ServerOperation(true)
.Events(events => events.Error("acc.mp.gridErrorDialog"))
.Read(read => read.Action(dataBindAction, controllerName, AddAntispinnerParameter(routeValues))));
}
and grid:
#(Html.Kendo()
.Grid<ValidatedClientAccountViewModel>()
.InitializeGrid(Naming.GridId(GridType.Upper), "GetClients, "ModelClients", new { modelTemplateId = Model.ModelId })
.DataSource(dataSource => dataSource
.Ajax()
.Model(model => model.Id(o => o.AccountId)))
.ToolBar(toolBar => toolBar.Template(
#<text>
<script type="text/javascript">
acc.mp.utils.bindLiveSearch($("##Naming.GridId(GridType.Upper) input[name='txtSearch']"), function () { $("##Naming.GridId(GridType.Upper) button[name='btnSearch']").click(); });
acc.mp.utils.searchGridFocus($("##Naming.GridId(GridType.Upper) input[name='txtSearch']"));
</script>
</text>))
.Columns(columns =>
{
columns.Bound(o => o.AccountId)
.ClientTemplate(ClientTemplates.UpperGridRowSelection)
.HtmlAttributes(new { style = "text-align: center" })
.HeaderTemplate(ClientTemplates.SelectAllCheckBox("cbLinkAll"))
.HeaderHtmlAttributes(new { style = "text-align: center" })
.Filterable(true)
.Sortable(false)
.Width(35);
columns.Bound(o => o.ClientReferenceNumber).Title(accountReference).HeaderHtmlAttributes(new { title = accountReference });
})
.EnableScrollingAndPaging(ModelPortfolioConfigurationManager.GridPageSize)
.Sortable()
.Events(events =>
{
events.DataBinding("acc.mp.clientAccounts.upperGrid.dataBinding");
events.DataBound("acc.mp.clientAccounts.upperGrid.dataBound");
events.Change("acc.mp.clientAccounts.upperGrid.rowSelect");
})
)
this is a bug in kendo, You can track the status of the issue here https://github.com/telerik/kendo-ui-core/issues/749

How can i highlight the Kendo grid cell by color change after update

I am using Kendo Ui Grid with MVC and SignalR. I can successfully perform the CRUD operations on grid using SignalR. I would like to notify clients by highlighting(By changing cell color) the updated cell. How can I achieve this with the following code:
#(Html.Kendo().Grid<Webapplication1.Models.ShipViewModel>()
.Name("ShipGrid")
.Columns(c =>{
c.Bound(m => m.Id).Hidden();
c.Bound(m => m.LocationViewModel)
.Title("Location1");
c.Bound(m => m.Location2ViewModel)
.Title("Location2");
c.Bound(m => m.boxSent);
c.Command(p =>
{
p.Edit().Text(" ").UpdateText(" ").CancelText(" ");
p.Destroy().Text(" ").HtmlAttributes(new { #title = "Cancel" });
});
})
.ToolBar(toolbar =>
{
toolbar.Create().Text("").HtmlAttributes(new { #title = "Add" });
})
.Editable(editable => editable
.DisplayDeleteConfirmation("DELETE.")
.Mode(Kendo.Mvc.UI.GridEditMode.PopUp)
.TemplateName("abcEditor")
)
.Events(events =>
{
events.Edit("edit");
})
.DataSource(dataSource => dataSource
.SignalR()
.Transport(tr => tr
.Promise("hubStart")
.Hub("mainHub")
.Client(c => c.Read("abc_Read").Create("abc_Insert").Update("abc_Update").Destroy("abc_Delete"))
.Server(s => s.Read("abc_Read").Create("abc_Insert").Update("abc_Update").Destroy("abc_Delete")))
.Schema(schema => schema
.Model(m => {
m.Id(p => p.Id);
m.Field(p => p.Location1ViewModel).DefaultValue(ViewData["DefaultLocation1"] as Webapplication1.Models.Location1ViewModel);
m.Field(p => p.Location2ViewModel).DefaultValue(ViewData["DefaultLocation2"] as Webapplication1.Models.DeliveryLocationViewModel);
})
)
)
)
I would like to Highlight the cell that is being updating here. Something like stock market data flashing. How can I achieve this?
I've done similar kind of thing. I don't know if that helps you. In your default view model add a extra property, say "Updated" as a boolean. Now every time you have update a row, put "Updated" as a true.
And in kendo grid add a new dataBound event.
.Events(events => events.DataBound("onDataBound"))
Now on JS use something like the following;
function onDataBound(arg) {
var itemsInActivityGrid = $("#ShippingGrid").data().kendoGrid.dataSource.data().length;
for (i = 0; i < itemsInActivityGrid; i++) {
if ($("#ShippingGrid").data().kendoGrid.dataSource.data()[i].Updated == true) {
$("#ShippingGrid .k-grid-content tr[data-uid='" + $("#ShippingGrid").data().kendoGrid.dataSource.data()[i].uid + "']").css("background-color", "orange");
}
}
}
Update: I don't know your logic. As far as you put on comments, you want to do something like online share dealing sites. Anyway, as far as I could, if you want to highlight individual cell in a row, add another extra field say "Column" along with "Updated"; it could be a string. Here you mark which cell you want to put the back ground colour from the backend. Say we've got it's value as "2".
for (i = 0; i < itemsInActivityGrid; i++)
{
var TableUID = $("#ShippingGrid").data().kendoGrid.dataSource.data()[i].uid;
var TableToColour = $("#ShippingGrid .k-grid-content tr[data-uid='" + TableUID + "']").parent().parent()[0];
var ColumnToColor = $("#ShippingGrid").data().kendoGrid.dataSource.data()[i].Column;
$(TableToColour.rows[0].cells[" + ColumnToColor + "]).select().attr("style","background-color:blue")
}
In case, you need to highlight multiple cells on the same row, in Column send something like "1,2,3,5"; where 1, 2, 3 and 5 represents the column numbers on the same row. And after ColumnToColor do some string parsing, put it into a for loop or something and colour;
Hope this helps. Thank you.
I have achieved this as below and its working fine:
in my .cshtml page
myHub.client.highlightRow = function (id) {
var data = $("#MyGrid").data("kendoGrid").dataSource.data();
for (var i = 0; i < data.length; i++) {
var dataItem = data[i];
if (dataItem.id == id) {
//alert(dataItem.uid);
$("#MyGrid").data("kendoGrid").tbody.find("tr[data-uid=" + dataItem.uid + "]").effect("highlight", { color: "#f35800" }, 3000);
}
}
};
And in my update/insert method in my SignalR Hub class:
Clients.Others.highlightRow(mygridViewModel.Id);

Kendo Pie Chart to Bar Chart

I am trying to go from a Kendo Pie chart to a Kendo Bar chart, my issue is the bar chart only returns one piece of data.
cshtml
`
<div id="pieEmployeeContainer">
#(Html.Kendo().Chart<SalesChart>().Name("pieEmployee").HtmlAttributes(new { style = "width: 90%;", #class = "fpos-chart" })
.Title("Top 10")
.Legend(false)
.Theme("bootstrap")
.DataSource(ds => ds.Read("SM_GetSalesByEmployees", "Home"))
.Series(s => s
.Pie(m => m.Total, m => m.Category)
.Padding(0)
)
.Tooltip(t => t
.Visible(true)
.Format("{0:c}")
.Template("#= category # <br /> #= kendo.format('{0:c}', value) # (#= kendo.format('{0:p}', percentage)#)")
)
.Events(e => e.SeriesClick("getByEmployee"))
.Deferred()
)
</div>
`
Controller
public ActionResult SM_GetSalesByEmployees()
{
List<SalesChart> items;
List<SalesChart> salesByEmpl;
using (StreamReader r = new StreamReader("C:\\Development\\Back Office Web\\Sandbox\\BackOffice.Web\\BackOffice.Web\\Content\\Data\\SalesByEmployee.json"))
{
string json = r.ReadToEnd();
items = JsonConvert.DeserializeObject<List<SalesChart>>(json);
salesByEmpl = items.GroupBy(l => l.EmployeeName)
.Select(lg =>
new SalesChart
{
Category = lg.Key,
Total = lg.Sum(w => w.Total)
}).ToList();
}
return new CustomJsonResult
{
Data = salesByEmpl
};
}
script
function getByEmployee(e)
{
var categorySelected = e.category;
var chart = $("#pieEmployee").data("kendoChart");
$.post("Home/GetSalesByEmployee?EmpName=" + categorySelected, function (results) {
chart.setDataSource(new kendo.data.DataSource({ data: results }));
});
chart.options.series[0].type = "bar";
chart.options.series[0].ValueAxis = "${Total}";
chart.options.series[0].categoryAxis = "{Category}";
chart.options.categoryAxis.baseUnit = "months";
chart.refresh();
}
I dont have a good enough reputation to post images, sorry about that.
The bar chart is only getting one data point and displaying that, rather than showing all data.
Any help is greatly appreciated.
I can't build out any test stuff but from quickly looking at it, the data format for the pie chart needs to be changed. It needs to be in percentages (the whole series needs to = 100) so you'll need to convert the data either in the view or the controller.

How do I display Kendo Grid inside Kendo Grid cell?

I am using Kendo Grid in my MVC application to display data. It works perfectly fine. But I would like to show another grid inside grid cell. I have done my research and tried different things, but I didn't find any solution. Please suggest.
Here is my code.
#(Html.Kendo().Grid<TimeSheetManagement.Models.ClientView>()
.Name( "Clients" )
.Columns( columns =>
{
columns.Bound( e => e.Name );
columns.Bound( e => e.Address );
columns.Bound( e => e.City );
columns.Bound( e => e.State );
columns.Bound( e => e.ZipCode );
columns.Template( e => e.Contacts ).ClientTemplate( "#= buildContactsGrid(data) #" );
columns.Bound( e => e.CreatedDate );
columns.Bound( e => e.CreatedBy );
columns.Bound( e => e.UpdatedDate );
columns.Bound( e => e.UpdatedBy );
columns.Bound( "" ).ClientTemplate( #Html.ActionLink( "Edit" , "Create" , new { clientId = "#=Id#" } , new { title = "Edit Client" } ).ToHtmlString() );
} )
.Pageable().Sortable().Filterable()
.AutoBind( true )
.DataSource( source => source.Ajax()
.PageSize( 20 )
.Read( read => read.Action( "GetClients" , "Client" ) )
)
)
Here is my JavaScript function.
<script>
function buildContactsGrid(client)
{
var htmlContacts = '';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '#Url.Action( "GetJsonContactsByClientId" )',
data: JSON.stringify({
'sClientId': client.Id
}),
dataType: "json",
async: false,
success: function (response) {
htmlContacts += "<table style='border:1px solid black;'><tr><th>First Name</th><th>Last Name</th><th>Role</th></tr><tr>";
$(response).each(function (index, item) {
htmlContacts +="<td>"+ item.FirstName +"</td><td>"+ item.LastName+"</td><td>"+item.Role +"</td></tr>";
});
htmlContacts += "</table>";
}
});
return htmlContacts;
}
</script>
I was able to build a table in JavaScript function and display in grid cell, but I would like to display Kendo Grid.
After spent some days on google by doing some research, I found this post link, they explained why client template not being bound on load.
Here is my grid inside grid cell:
columns.Template( e => "" ).Title("Contacts").ClientTemplate(
Html.Kendo().Grid<TimeSheetManagement.Models.ContactView>()
.Name( "Clients_#=Id#" )
.Columns( c =>
{
c.Bound( e1 => e1.FullName );
c.Bound( e1 => e1.Role );
c.Bound( e1 => e1.Email );
c.Bound( e1 => e1.PhoneNumber );
} )
.AutoBind( true )
.DataSource( source1 => source1.Ajax()
.PageSize( 5 )
.Read( read1 => read1.Action( "GetContactsByClientId" , "Client" , new { sClientId = "#=Id#" } ) )
)
.ToClientTemplate()
.ToHtmlString()
);
And I have this event on the grid.
.Events( e => e.DataBound( "onGridDataBound" ) )
And finally I added this code in the script.
function onGridDataBound(e)
{
$('#Clients script').appendTo(document.body);
}
Here is the output as I expected. Let me know if you have any questions.

Resources