Telerik Forums
UI for ASP.NET MVC Forum
1 answer
123 views

Hi All

I just want to learn when i do custom excel export i want to get filtered data from ajax request

I tried .view() but it just return data on screen like if i have 20 data and show just 10 of them i get just 10 of them

on the other hand i tried .data() function but that is returning all data and i have really huge data like 15k data

 

How to get just filtered data?

 

here my grid and js functon and controller

@( Html.Kendo().Grid<Orpac.Controllers.DashboardsController.ATGAlerts>()
                 .Name("grdProductAlert").AutoBind(false)
                 .HtmlAttributes("width: 100%;cellpadding:0;")
                 .DataSource(d => d.Ajax().Read(r => r.Action("GridProductAlertBinding", "Dashboards").Type(HttpVerbs.Get)).ServerOperation(false))
                  .Columns(columns =>
                  {
                      columns.Bound(e => e.BelIdent).Title("Id").Width("auto");
                      columns.Bound(e => e.StationCode).Title("Station Code").Width("auto");
                      columns.Bound(e => e.StationName).Title("Station Name").Width("auto");
                      columns.Bound(e => e.BelTarih).Title("Date Time").ClientTemplate("#= kendo.toString(BelTarih, 'MM/dd/yyyy') #").ClientGroupHeaderTemplate("DateTime" + ": #=  kendo.toString(value, 'MM/dd/yyyy') #").Width("auto");
                      columns.Bound(e => e.BelInsTime).Title("Alert Time").ClientTemplate("#= kendo.toString(BelInsTime, 'MM/dd/yyyy HH:mm tt') #").ClientGroupHeaderTemplate("DateTime" + ": #=  kendo.toString(value, 'MM/dd/yyyy HH:mm tt') #").Width("auto");
                      columns.Bound(e => e.ProductCode).Title("Product Code").Width("auto");
                      columns.Bound(e => e.BelAlarm).Title("Alarm").Width("auto");
                      columns.Bound(e => e.BelLevelPerc).Title("Level %").Width("auto");
                      columns.Bound(e => e.BelTotCapacity).Title("Total Capacity").Width("auto");
                      columns.Bound(e => e.BelFuelVolume).Title("Available Volume").Width("auto");
                  }
                )
                .ToolBar(toolBar =>
                {
                    toolBar.Custom().Text(" ").HtmlAttributes(new { @class = "btnexcel", href = "#", onclick= "testexcel()" });
                    toolBar.Custom().Text((string)ViewData["ClearFilter"]).HtmlAttributes(new { @class = "k-button", id = "cleargrid", href = "#", onclick = "clearFiltersFuelLevel()" });
                }
                )
                .Selectable()
                .Sortable()
                .Pageable(pageable => pageable
                .Refresh(true)
                .PageSizes(true)
                .ButtonCount(5))
                .Filterable(filterable => filterable
                .Extra(false)
                .Operators(operators => operators
                .ForString(str => str.Clear()
                .StartsWith((string)ViewData["Startswith"])
                .Contains((string)ViewData["Contains"])
                ))
                )
                .Groupable()
                .Scrollable(scrolling => scrolling.Height("100%"))
                .Resizable(config =>
                {
                    config.Columns(true);
                })
                .Reorderable(config =>
                {
                    config.Columns(true);
                })
                .ColumnMenu()
                )

here my js

function testexcel() {
    var grid = $("#grdProductAlert").data('kendoGrid');
 
    var viewdata = {
        data: grid.dataSource.view()
    };
 
 
 
    var url = '../Dashboards/ExportCsvList';
    $.ajax({
        type: "POST",
        url: url,
        traditional:true,
        data: { request: viewdata.data },
        success: function (msg) {
             
        }
    });
}

 

here my conroller

public FileResult ExportCsvList(List<ATGAlerts> request)
        {
            //Get the data representing the current grid state - page, sort and filter
            var products = request;
 
            using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
            {
                /* Create the worksheet. */
 
                SpreadsheetDocument spreadsheet = Excel.CreateWorkbook(stream);
                Excel.AddBasicStyles(spreadsheet);
                Excel.AddAdditionalStyles(spreadsheet);
                Excel.AddWorksheet(spreadsheet, "ProductAlert");
                Worksheet worksheet = spreadsheet.WorkbookPart.WorksheetParts.First().Worksheet;
 
                //create columns and set their widths
 
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 1, "Ident", false, false);
                Excel.SetColumnWidth(worksheet, 1, 50);
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 2, "Station Code", false, false);
                Excel.SetColumnWidth(worksheet, 2, 50);
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 3, "Station  Name", false, false);
                Excel.SetColumnWidth(worksheet, 3, 50);
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 4, "Date Time", false, false);
                Excel.SetColumnWidth(worksheet, 4, 50);
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 5, "Alert Time", false, false);
                Excel.SetColumnWidth(worksheet, 5, 50);
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 6, "Product Code", false, false);
                Excel.SetColumnWidth(worksheet, 6, 50);
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 7, "Alarm", false, false);
                Excel.SetColumnWidth(worksheet, 7, 50);
 
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 8, "Level %", false, false);
                Excel.SetColumnWidth(worksheet, 8, 50);
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 9, "Total Capacity", false, false);
                Excel.SetColumnWidth(worksheet, 9, 50);
 
 
                Excel.SetColumnHeadingValue(spreadsheet, worksheet, 10, "Available Volume", false, false);
                Excel.SetColumnWidth(worksheet, 10, 50);
 
                /* Add the data to the worksheet. */
 
                // For each row of data...
                for (int idx = 0; idx < products.Count; idx++)
                {
                    // Set the field values in the spreadsheet for the current row.
                    Excel.SetCellValue(spreadsheet, worksheet, 1, (uint)idx + 2, products[idx].BelIdent.ToString(), false, false);
 
                    Excel.SetCellValue(spreadsheet, worksheet, 2, (uint)idx + 2, products[idx].StationCode, false, false);
 
                    Excel.SetCellValue(spreadsheet, worksheet, 3, (uint)idx + 2, products[idx].StationName, false, false);
                    Excel.SetCellValue(spreadsheet, worksheet, 4, (uint)idx + 2, products[idx].BelTarih.Value, 1, false);
                    Excel.SetCellValue(spreadsheet, worksheet, 5, (uint)idx + 2, products[idx].BelInsTime.Value, 1, false);
                    Excel.SetCellValue(spreadsheet, worksheet, 6, (uint)idx + 2, products[idx].ProductCode, false, false);
 
                    Excel.SetCellValue(spreadsheet, worksheet, 7, (uint)idx + 2, products[idx].BelAlarm, false, false);
 
                    Excel.SetCellValue(spreadsheet, worksheet, 8, (uint)idx + 2, products[idx].BelLevelPerc.ToString(), false, false);
 
                    Excel.SetCellValue(spreadsheet, worksheet, 9, (uint)idx + 2, products[idx].BelTotCapacity.ToString(), false, false);
                    Excel.SetCellValue(spreadsheet, worksheet, 10, (uint)idx + 2, products[idx].BelFuelVolume.ToString(), false, false);
 
                }
 
                /* Save the worksheet and store it in Session using the spreadsheet title. */
 
                worksheet.Save();
                spreadsheet.Close();
 
                return File(stream.ToArray(),   //The binary data of the XLS file
                "application/vnd.ms-excel", //MIME type of Excel files
                "ProductAlert.xlsx");
            }
        }

 

please help

Nikolay
Telerik team
 answered on 01 Jun 2020
1 answer
2.0K+ views

  Hi All

Is it possible to send Kendo Grid DataSourceRequest as javascript parameter to conroller?

 

I just want to do something like this

var url = '../Dashboards/ExportCsvList';
$.ajax({
    type: "POST",
    url: url,
    traditional:true,
    data: { request: datarequest} // i want to send as paramter
    success: function (msg) {
         
    }
});

and i want to catch that as in example below

public FileResult ExportCsvList([DataSourceRequest]DataSourceRequest request)
{
           //do smth...
}

 

Is it possible?

 

Thanks

Alex Hajigeorgieva
Telerik team
 answered on 01 Jun 2020
1 answer
1.3K+ views

Hi All,

 

I'm using kendo mvc grid and sometimes i have 15k data or 100k data and sometimes i need to export excel them with 5k data and using your export excel function but it creates problem to me

Is there any limitation for row value? How can i handle this? 

I want to export excel all my grids from toolbar actions... How can you help me?

Here is my grid..

@(Html.Kendo().Grid<ATGAlerts>()
                    .Name("grdWaterAlert").AutoBind(false)
                    .HtmlAttributes("width: 100%;cellpadding:0;")
                    .DataSource(d => d.Ajax().Read("GridWaterAlertBinding", "Dashboards"))
                    .Columns(columns =>
                    {
                        columns.Bound(e => e.BelIdent).Title("Id").Width("auto");
                        columns.Bound(e => e.StationCode).Title("Station Code").Width("auto");
                        columns.Bound(e => e.StationName).Title("Station Name").Width("auto");
                        columns.Bound(e => e.BelTarih).Title("DateTime").ClientTemplate("#= kendo.toString(BelTarih, 'MM/dd/yyyy') #").ClientGroupHeaderTemplate("DateTime" + ": #=  kendo.toString(value, 'MM/dd/yyyy') #").Width("auto");
                        columns.Bound(e => e.BelInsTime).Title("Alert Time").ClientTemplate("#= kendo.toString(BelInsTime, 'MM/dd/yyyy HH:mm tt') #").ClientGroupHeaderTemplate("DateTime" + ": #=  kendo.toString(value, 'MM/dd/yyyy HH:mm tt') #").Width("auto");
                        columns.Bound(e => e.BelTankId).Title("Tank ID").Width("auto");
                        columns.Bound(e => e.ProductCode).Title("Product Code").Width("auto");
                        columns.Bound(e => e.BelAlarm).Title("Alarm").Width("auto");
                        columns.Bound(e => e.BelTotCapacity).Title("Total Capacity").Width("auto");
                        columns.Bound(e => e.BelWaterVol).Title("Water Volume").Width("auto");
                    })
                    .ToolBar(toolBar =>
                    {
                        toolBar.Excel().HtmlAttributes(new { @class = "btnexcel" }).Text(" ").IconClass("k-i-excel");
                        toolBar.Custom().Text((string)ViewData["ClearFilter"]).HtmlAttributes(new { @class = "k-button", id = "cleargrid", href = "#", onclick = "clearFiltersWaterLevel()" });
                    })
                    .Excel(excel => excel.FileName("WaterAlert.xlsx").Filterable(true))
                    .Selectable()
                    .Sortable()
                    .Pageable(pageable => pageable
                    .Refresh(true)
                    .PageSizes(true)
                    .ButtonCount(5))
                    .Filterable(filterable => filterable
                    .Extra(false)
                    .Operators(operators => operators
                    .ForString(str => str.Clear()
                    .StartsWith((string)ViewData["Startswith"])
                    .Contains((string)ViewData["Contains"])
                    ))
                    )
                    .Groupable()
                    .Scrollable(scrolling => scrolling.Height("100%"))
                    .Resizable(config =>
                    {
                    config.Columns(true);
                    })
                    .Reorderable(config =>
                    {
                    config.Columns(true);
                    })
                    .ColumnMenu()
                )

 

 

 

Thanks for help!

Nikolay
Telerik team
 answered on 01 Jun 2020
13 answers
1.2K+ views

I have a simple grid with Add/Edit functionality enabled and it's using the popup grid edit mode.  When in that mode, a drop down is not setting the selected value as it should.  If I use inline, everything works like a charm. 

 

When the add/edit form is rendered, the selected value for the record is not being set in the drop down.  When you submit the form, the value is always correct.  The default value is sent when the selected value drop down list was not changed.  The same goes for editing (value being the previously saved value).

 

This behavior seems to only happen on combo boxes and drop down lists and it's limited to the popup form.  Below is my view, editor template, and the model.  The field in question is Chaperone.

Thank You!

View:

<%= Html.Kendo().Grid<ChaperoneLogViewModel>()
        .Name("ChaperoneLog")
        .DataSource(datasource => datasource.Ajax()
            .Read("Select", "ChaperoneLogList")
            .Update("Update", "ChaperoneLogList")
            .Create("Create", "ChaperoneLogList")
            .Destroy("Delete", "ChaperoneLogList")
            .Model(model => {
                model.Id(field => field.Id);
                model.Field(field => field.Name);
                model.Field(field => field.Chaperone)
                    .DefaultValue(HttpContext.Current.User.Identity.Name);
            })
            .Filter(filter =>
            {
                filter.Add(field => field.Date)
                    .IsLessThanOrEqualTo(DateTime.Now)
                    .And()
                    .IsGreaterThanOrEqualTo(DateTime.Now.AddDays(-7));
                filter.Add(field => field.Chaperone)
                    .IsEqualTo(HttpContext.Current.User.Identity.Name);
            })
            .PageSize(20)
        )
        .EnableCustomBinding(true)
        .ToolBar(toolbar =>
        {
            toolbar.Create();
            toolbar.Excel();
        })
        .Excel(excel =>
        {
            excel.AllPages(true);
            excel.FileName("ChaperoneList_" + DateTime.Now.ToShortDateString()+".xlsx");
            excel.Filterable(true);
        })
        .Events(events => events.Edit("loadResearch"))
        .Columns(columns =>
        {
            columns.Command(commands =>
            {
                commands.Destroy().Text(" ");
                commands.Edit().Text(" ").CancelText(" ").UpdateText(" ");
            }).Width(80);
            columns.Bound(column => column.Date).AsDate().Width(90);
            columns.Bound(column => column.Name).Title("Topic");
            columns.Bound(column => column.Symbol).Title("S").Width(60);
            columns.Bound(column => column.BankerListDisp);
            columns.Bound(column => column.ResearchListDisp);
            columns.Bound(column => column.Other);
            columns.Bound(column => column.Chaperone).ClientTemplate("#= ChaperoneDisplay #").Title("C").Width(60);
        })
        .Pageable()
        .Sortable(sort => sort.SortMode(Kendo.Mvc.UI.GridSortMode.SingleColumn))
        .Filterable(filter => filter.Mode(GridFilterMode.Menu))
        .Scrollable(scroll => scroll.Height("auto"))
        .Editable(edit => edit.Mode(Kendo.Mvc.UI.GridEditMode.InLine))
        .Selectable()
        .Resizable(resizing => resizing.Columns(true))
 
%>

 

EditorTemplate:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%
    var users = Roles.GetUsersInRole("StandardUser");
    var profs = users.Select(WebProfile.GetProfile).ToList();
 
    var list = new List<SelectListItem>();
    list.AddRange(profs.Select(
        x => new SelectListItem
        {
            Text = String.Format("{1}, {0}", x.FirstName, x.LastName),
            Value = Html.Encode(x.UserName)
        })
    );
 
    list = list.OrderBy(x => x.Text).ToList();
%>
 
<%=Html.Kendo().DropDownList()
    .Name("Chaperone")
    .DataValueField("Value")
    .DataTextField("Text")
    .HtmlAttributes(new {style = "width: 160px; "})
    .BindTo(list) 
    .OptionLabel("Select a Chaperone...")  
    .Value(Model.ToString())
%>

 

Model:

namespace CyfPortal.ApplicationServices.ViewModels
{
    [DisplayName("Chaperone Log")]
    public class ChaperoneLogViewModel : ViewModel<ChaperoneLog>
    {
        public ChaperoneLogViewModel()
        {
            Chaperone = HttpContext.Current.User.Identity.Name;
        }
 
        [ScaffoldColumn(false)]
        [Map("Id", ReadOnly = true)]
        public int Id { get; set; }
 
        [DataType(DataType.Date)]
        public DateTime Date { get; set; }
 
        [UIHint("Symbols")]
        public string Symbol { get; set; }
 
        [Display(Name = "Topic")]
        public string Name { get; set; }
 
        [UIHint("SeniorBankers")]
        public string Banker { get; set; }
 
        public string AddBanker { get; set; }
 
        [UIHint("Analysts")]
        public string Research { get; set; }
 
        public string AddResearch { get; set; }
 
        [DataType(DataType.MultilineText)]
        public string Other { get; set; }
 
        [UIHint("Chaperone")]
        public string Chaperone { get; set; }
 
        public string ChaperoneDisplay
        {
            get
            {
                var prof = WebProfile.GetProfile(Chaperone);
                var fi = "";
                var li = "";
                if (!String.IsNullOrEmpty(prof.FirstName)) fi = prof.FirstName.Substring(0, 1);
                if (!String.IsNullOrEmpty(prof.LastName)) li = prof.LastName.Substring(0, 1);
                return fi+li;
            }
        }
 
        public string[] ResearchList
        {
            get
            {
                if (String.IsNullOrEmpty(Research))
                {
                    return new string[] { };
                }
                return Research.Split(',');
            }
        }
 
        [Display(Name = "Research")]
        public string ResearchListDisp
        {
            get
            {
                if (String.IsNullOrEmpty(AddResearch)) return Research;
                return Research + ", " + AddResearch;
            }
        }
 
        public string[] BankerList
        {
            get
            {
                if (String.IsNullOrEmpty(Banker))
                {
                    return new string[] { };
                }
                return Banker.Split(',');
            }
        }
 
        [Display(Name = "Banker")]
        public string BankerListDisp
        {
            get
            {
                if (String.IsNullOrEmpty(AddBanker)) return Banker;
                return Banker + ", " + AddBanker;
            }
        }
    }
}

Sivaramakrishna Reddy
Top achievements
Rank 1
Veteran
 answered on 30 May 2020
2 answers
1.0K+ views

I have declared a DatePicker.  Normally, the popup would only open when the user clicks the button and the user can free hand a date into the text field.  I want to alter these two behaviors.

 

1. When the user mouse clicks anywhere on the DatePicker, even in the text field, the popup opens.

2. Prevent the user from typing anything into the text field.  The user will be forced to use the popup to select a date.

Eric
Top achievements
Rank 1
Veteran
Iron
 answered on 29 May 2020
3 answers
163 views

Hi ,

I have a kendo dropdownlist outside grid and toolbar button inside grid, I need to validate the dropdownlist selection  when toolbar button inside grid is clicked , is there any way to validate the dropdowlist when no records selected from toolbar click, Help will be appreciated!!!

 

Regards

Mohmmed 

Nikolay
Telerik team
 answered on 29 May 2020
3 answers
1.3K+ views

I saw that when sending the Model state on the read method of the grid it is ignored? Is this function as design? How to implement this on every grid

public async Task<ActionResult> GetViewModels([DataSourceRequest]DataSourceRequest request)
{
    var models = System.Array.Empty<ViewModel>();
    ModelState.AddModelError(string.Empty, "Just to test something");
    var result = await models.ToDataSourceResultAsync(request, ModelState).ConfigureAwait(false);
    return Json(result);
}
Nikolay
Telerik team
 answered on 29 May 2020
3 answers
2.2K+ views

Is possible set the background color of each item in list of multiselect object? 

Thank you

 

Neli
Telerik team
 answered on 28 May 2020
3 answers
360 views

I have a form with a couple of switchfor controls on them. They are bond to Boolean properties of my model. When calling a reset on the form, these controls do not revert back to the original value as expected.

 

<div class="col-1">
                        <div class="form-group">
                            <label asp-for="DoNotContact">Ne pas contacter</label><br />
                            @(Html.Kendo().SwitchFor(m => m.DoNotContact)    )
             </div>

 </div>

What am I doing wrong?

 

 

 

Nikolay
Telerik team
 answered on 28 May 2020
2 answers
732 views

Hi,

 

Any option to set the focus on page load to the first control of the form. A jquery function with focus() doensn't seem to work

Regards,

Bart

Bart
Top achievements
Rank 1
 answered on 28 May 2020
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
Upload
ComboBox
MultiSelect
ListView
Window
TabStrip
Menu
Installer and VS Extensions
Spreadsheet
AutoComplete
TreeList
Gantt
PanelBar
NumericTextBox
Filter
ToolTip
Map
Diagram
Button
PivotGrid
Form
ListBox
Splitter
Application
FileManager
Sortable
Calendar
View
MaskedTextBox
PDFViewer
TextBox
Toolbar
MultiColumnComboBox
Dialog
DropDownTree
Checkbox
Slider
Switch
Notification
ListView (Mobile)
Pager
Accessibility
ColorPicker
DateRangePicker
Wizard
Security
Styling
Chat
MediaPlayer
TileLayout
DateInput
Drawer
SplitView
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
Template
Badge
LinearGauge
ModalView
ResponsivePanel
TextArea
Breadcrumb
ExpansionPanel
Licensing
Rating
ScrollView
ButtonGroup
CheckBoxGroup
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
Localization
MultiViewCalendar
PopOver (Mobile)
Ripple
ScrollView (Mobile)
Switch (Mobile)
PivotGridV2
FlatColorPicker
ColorPalette
DropDownButton
AIPrompt
PropertyGrid
ActionSheet (Mobile)
BulletGraph
Button (Mobile)
Collapsible
Loader
CircularGauge
SkeletonContainer
Popover
HeatMap
Avatar
ColorGradient
CircularProgressBar
SplitButton
StackLayout
TimeDurationPicker
Chip
ChipList
DockManager
ToggleButton
Sankey
OTPInput
ChartWizard
SpeechToTextButton
InlineAIPrompt
TimePicker
StockChart
RadialGauge
ContextMenu
ArcGauge
AICodingAssistant
+? more
Top users last month
Edmond
Top achievements
Rank 1
Iron
fabrizio
Top achievements
Rank 2
Iron
Veteran
RobMarz
Top achievements
Rank 2
Iron
Fakhrul
Top achievements
Rank 1
Iron
Tejas
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Edmond
Top achievements
Rank 1
Iron
fabrizio
Top achievements
Rank 2
Iron
Veteran
RobMarz
Top achievements
Rank 2
Iron
Fakhrul
Top achievements
Rank 1
Iron
Tejas
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?