Telerik Forums
UI for ASP.NET MVC Forum
4 answers
852 views

Hello.

I am using the UI for ASP.NET MVC Grid version 2016.3.914.545 with Telerik DataAccess version 2016.1.224.1 with a MSSQLLocalDB for development.

As long as there is no filter or group used in the grid everything is working. If the user filters, even a simple "=", the request times out. Using the DataAccess Profiler I found the reason. The generated SQL statement reads all records. Not only the required 10. Which takes about three minutes with subsequent requests to get the detailed data.

The grid config in my view:

01.@(Html.Kendo().Grid<CalendarEventViewModel>()
02.    .Name(componentName: "eventGrid")
03.    .Pageable()
04.    .Scrollable(s => { s.Height(value: "auto"); s.Enabled(value: true); })
05.    .Filterable()
06.    .Groupable()
07.    .Sortable(s => s.Enabled(value: true))
08.    .Resizable(r => r.Columns(value: true))
09.    .Selectable()
10.    .Columns(columns => {
11.        columns.Bound(c => c.Operation.OperationIdFormatted)
12.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.MasterSystemId)}" })
13.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.MasterSystemId)}", resourceSet: ResourceSet.Properties));
14.        columns.Bound(c => c.Title)
15.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Title)}" })
16.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Title)}", resourceSet: ResourceSet.Properties));
17.        columns.Bound(c => c.Workplace.Label)
18.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Workplace)}" })
19.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Workplace)}", resourceSet: ResourceSet.Properties));
20.        columns.Bound(c => c.Description)
21.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Description)}" })
22.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Description)}", resourceSet: ResourceSet.Properties));
23.        columns.Bound(c => c.StartWeek)
24.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.StartWeek)}" })
25.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.StartWeek)}", resourceSet: ResourceSet.Properties));
26.        columns.Bound(c => c.EndWeek)
27.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.EndWeek)}" })
28.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.EndWeek)}", resourceSet: ResourceSet.Properties));
29.        columns.Bound(c => c.Start).Format(value: "{0:F}")
30.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Start)}" })
31.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.Start)}", resourceSet: ResourceSet.Properties));
32.        columns.Bound(c => c.End).Format(value: "{0:F}")
33.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.End)}" })
34.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(CalendarEventViewModel)}.{nameof(CalendarEventViewModel.End)}", resourceSet: ResourceSet.Properties));
35.        columns.Bound(c => c.Operation.TimeSpanPerUnit)
36.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.TimePerUnit)}" })
37.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.TimePerUnit)}", resourceSet: ResourceSet.Properties))
38.            .ClientTemplate(value: "#if (data.TimeSpanPerUnit) {# #:kendo.toString(TimeSpanPerUnit.Hours, '00')#:#:kendo.toString(TimeSpanPerUnit.Minutes, '00')#:#:kendo.toString(TimeSpanPerUnit.Seconds, '00')# #}#");
39.        columns.Bound(c => c.Operation.QuantityToProduce).Format(value: "{0:n}")
40.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.QuantityToProduce)}" })
41.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.QuantityToProduce)}", resourceSet: ResourceSet.Properties));
42.        columns.Bound(c => c.Operation.QuantityConfirmed).Format(value: "{0:n}")
43.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.QuantityConfirmed)}" })
44.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.QuantityConfirmed)}", resourceSet: ResourceSet.Properties));
45.        columns.Bound(c => c.Operation.QuantityOpen).Format(value: "{0:n}")
46.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.QuantityOpen)}" })
47.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.QuantityOpen)}", resourceSet: ResourceSet.Properties));
48.        columns.Bound(c => c.Operation.Length)
49.            .HeaderHtmlAttributes(new { data_resource_set = ResourceSet.Properties, data_resource_id = $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.Length)}" })
50.            .Title(Html.GetGlobalResourceString(resourceKey: $"{nameof(OperationViewModel)}.{nameof(OperationViewModel.Length)}", resourceSet: ResourceSet.Properties))
51.            .ClientTemplate(value: "#if (data.Length) {# #:kendo.toString(Length.Hours, '00')#:#:kendo.toString(Length.Minutes, '00')#:#:kendo.toString(Length.Seconds, '00')# #}#")
52.            .EditorTemplateName(templateName: "TimeSpan");
53.    })
54.    .DataSource(d => d.Ajax().Model(m => {
55.            m.Id(f => f.Id);
56.            m.Field(f => f.Id).Editable(enabled: false);
57.        })
58.        .Events(e => e.Error(handler: "scheduler_error"))
59.        .Read(read => read.Route(SchedulerControllerRoute.PostOperationEvents, new RouteValueDictionary { { "culture", UICulture.ToLower() } }))
60.        .Update(update => update.Route(SchedulerControllerRoute.PostUpdate, new RouteValueDictionary { { "culture", UICulture.ToLower() } }))
61.        //.Destroy(destroy => destroy.Route(OperationControllerRoute.PostDestroy, new RouteValueDictionary { { "culture", UICulture.ToLower() } }))
62.        .Create(create => create.Route(SchedulerControllerRoute.PostCreate, new RouteValueDictionary { { "culture", UICulture.ToLower() } }))
63.    )
64.    .ClientDetailTemplateId(id: "operationDetailTemplate")
65.    .Events(e => e.DataBound(handler: "dispatcher.onGridDataBound"))
66.    .Deferred()
67.)

The read service:

01.public IQueryable<CalendarEventViewModel> OperationEvents() {
02.    IQueryable<CalendarEventViewModel> result = new CalendarEventViewModel[] { }.AsQueryable();
03.    FetchStrategy oldStrategy = _db.FetchStrategy;
04.    var strategy = new FetchStrategy();
05.    strategy.LoadWith<WorkOrder>(w => w.Endproduct);
06.    _db.FetchStrategy = strategy;
07.    PreferenceProfile activeProfile = HttpContext.Current.Session.Get<PreferenceProfile>(SessionKey.ActiveProfile);
08.    if (activeProfile != null) {
09.        string masterSystemId = activeProfile.Company.MasterSystemId;
10.        result =_db.CalendarEvents.Where(ce => ce.Operation != null && ce.Operation.MasterSystemHierarchy==masterSystemId && !filteredStates.Contains(ce.Operation.ProcessingStatus) && ce.Operation.WorkOrder.QuantityToProduce-ce.Operation.QuantityConfirmed > 0)
11.            .Select(ce => _mapper.Map<CalendarEventViewModel>(ce));
12.    }
13.    _db.FetchStrategy = oldStrategy;
14.    return result;
15.}

In the controller itself nothing special happens:

1.public JsonResult OperationEvents([DataSourceRequest] DataSourceRequest request) {
2.    IQueryable<CalendarEventViewModel> result = ((ISchedulerEventService) crudService).OperationEvents();
3.    return Json(result.ToDataSourceResult(request));
4.}

The SQL generated after setting a filter:

01.SELECT
02.    a.[Id] AS COL1,
03.    a.[ActivityStatus] AS COL2,
04.    a.[BackgroundColor] AS COL3,
05.    a.[EventType] AS COL4,
06.    a.[Description] AS COL5,
07.    a.[en] AS COL6,
08.    a.[EventType] AS COL7,
09.    a.[IsAllDay] AS COL8,
10.    a.[OperationId] AS COL9,
11.    a.[OperationId] AS COL10,
12.    a.[RecurrenceException] AS COL11,
13.    a.[RecurrenceRule] AS COL12,
14.    a.[strt] AS COL13,
15.    a.[Status] AS COL14,
16.    a.[Title] AS COL15,
17.    a.[WorkplaceId] AS COL16,
18.    a.[WorkplaceId] AS COL17
19. 
20.FROM [CalendarEvent] a
21. 
22.JOIN [Operation] AS b
23.  ON (a.[OperationId] = b.[Id])
24. 
25.JOIN [WorkOrder] AS c
26.  ON (b.[WorkOrderId] = c.[Id])
27. 
28.WHERE a.[OperationId] IS NOT NULL
29.  AND b.[MasterSystemHierarchy] = @p0
30.  AND NOT ((b.[ProcessingStatus] IN (@p1, @p2)))
31.  AND c.[QuantityToProduce] - b.[QuantityConfirmed] > 0
32. 
33.ORDER BY COL1

The grid filter, Workplace.Label="Something", is missing and the TOP() statement is missing. Seems Like ToDataSourceResult wants to laod everything into memory and do the filtering itself.

How can I convince ToDataSourceResult from taking only the needed and filterd 10 rows? Does it help if I add the filters in my where clause as request filters?

Side note for the DataAccess team: I configured logging of the stack trace, but the profiler says there is none. My configuration:

config.Logging.LogEvents = LoggingLevel.Verbose;
config.Logging.StackTrace = true;
config.Logging.EventStoreCapacity = 10000;
config.Logging.MetricStoreCapacity = 3600;
config.Logging.MetricStoreSnapshotInterval = 1000;
config.Logging.Downloader.EventText = true;
config.Logging.Downloader.EventPollSeconds = 1;
config.Logging.Downloader.MetricPollSeconds = 1;
config.Logging.Downloader.Filename = "C:\\Temp\\OALog";
config.Logging.Downloader.EventBinary = true;
config.Logging.Downloader.MetricBinary = true;

Kind regards

Bernd

Bernd
Top achievements
Rank 2
 answered on 23 Sep 2016
3 answers
307 views

Hi,

I am using a date picker to edit the date displayed on my grid.

@(Html.Kendo().DatePicker()
                 .Name("Date")
                 .Value("Value")
                 .Format("MM/dd/yyyy")
                 .HtmlAttributes(new { style = "width: 30%" })
)
The problem is while saving the date it gets saved as shown in the attachment.

I just want it to be saved in the format (mm/dd/yyyy) and I dont want those extra labels such as indian standard time etc.

Can anyone help?

Regards,

Adhip

 

Eduardo Serra
Telerik team
 answered on 22 Sep 2016
1 answer
180 views
Hello, i have a problem with my Grid and Persist-State, when i use "Load" state, the grid lose all properties(Edit and Remove bottons, Tooltips and styles).

This is the Code.

@{
                      string quote = "\"";
                      var javaScriptSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                      string jsonString = javaScriptSerializer.Serialize(DictionaryByControls.TagsConfirmationPanel);
 
                  }
                  @(Html.Kendo().Grid<ControlGAS.DataAccess.Entities.Customer>()
                      .Name("GridCustomers")
                      .Columns(columns =>
                      {
                          columns.Bound(customer => customer.Id).Title("ID").Filterable(f => f.UI("filterById")).HtmlAttributes(new { @style = "white-space: nowrap;" });
                          columns.Bound(customer => customer.Denomination).Title(ControlGAS.Office.Resources.Resources.ControlGAS.Denomination).Filterable(f => f.UI("filterByName")).HtmlAttributes(new { @style = "white-space: nowrap;" });
                          columns.Bound(customer => customer.Code).Title(ControlGAS.Office.Resources.Resources.ControlGAS.Code).Filterable(f => f.UI("filterByCode")).HtmlAttributes(new { @style = "white-space: nowrap;" });
                          columns.Bound(customer => customer.Address).Title(ControlGAS.Office.Resources.Resources.ControlGAS.Address).Filterable(f => f.UI("filterByAddress")).HtmlAttributes(new { @style = "white-space: nowrap;" });
                          columns.Bound(customer => customer.City).Title(ControlGAS.Office.Resources.Resources.ControlGAS.City).Filterable(f => f.UI("filterByCity")).HtmlAttributes(new { @style = "white-space: nowrap;" });
                          columns.Bound(customer => customer.FiscalIdentification).Title(ControlGAS.Office.Resources.Resources.ControlGAS.FiscalIdentification).Filterable(f => f.UI("filterByFiscalId")).HtmlAttributes(new { @style = "white-space: nowrap;" });
                          columns.Template(customer => { }).ClientTemplate(
                              "<a href=" + quote + @Url.Action("Editing", "Customer", new { customerId = "#=Id#" }) + quote + "><i class='font-size-20 icon md-edit margin-right-10' aria-hidden='true'></i></a>" + "" +
                              "<a class='cursor-pointer' data-customer='#=Denomination#'data-id-customer='#=Id#' data-resource = '" + jsonString + "'  data-control='btn-delete-customer'><i class='font-size-20 icon md-delete margin-right-10' aria-hidden='true'></i></a>")
                              .Title("Actions").Width(100);
 
                      })
                      .ColumnMenu()
                      .Scrollable(s => s.Height("100%"))
                      .Sortable()
                      .Groupable(g => g.Messages(m => m.Empty(ControlGAS.Office.Resources.Resources.ControlGAS.Drag)))
                      .Pageable(p => p
                                      .Refresh(true)
                                      .PageSizes(true)
                                      .ButtonCount(5)
                                      .PreviousNext(true)
                                      .Messages(m => m.ItemsPerPage(ControlGAS.Office.Resources.Resources.ControlGAS.ItemPerPage)))
 
                      .DataSource(
                          dataSource => dataSource
                          .Ajax()
                          .Read(read => read.Action("GetCustomers", "Customer"))
                      )
                      .Resizable(r => r.Columns(true))
                      .Reorderable(r => r.Columns(true))
                      .ClientDetailTemplateId("master")
                      .Filterable(filter => filter.Mode(GridFilterMode.Row)
                            .Extra(false)
                            .Operators(operators => operators
                                .ForString(str => str.Clear()
                                    .StartsWith(ControlGAS.Office.Resources.Resources.ControlGAS.StartsWith)
                                    .IsEqualTo(ControlGAS.Office.Resources.Resources.ControlGAS.IsEqualTo)
                                    .IsNotEqualTo(ControlGAS.Office.Resources.Resources.ControlGAS.IsNotEqualTo)
 
                               )
                               .ForNumber(num => num.Clear()
                                    .IsEqualTo(ControlGAS.Office.Resources.Resources.ControlGAS.IsEqualTo)
                                    .IsNotEqualTo(ControlGAS.Office.Resources.Resources.ControlGAS.IsNotEqualTo)
                                    .IsNull(ControlGAS.Office.Resources.Resources.ControlGAS.IsNull)
                                    .IsLessThan(ControlGAS.Office.Resources.Resources.ControlGAS.IsLessThan)
                                    .IsGreaterThan(ControlGAS.Office.Resources.Resources.ControlGAS.IsGreaterThan))
 
                          )
                      )
                      .Events(events => events.DataBound("dataBound"))
                  )

Save State

function GetDataGrid() {
    var grid = $("#GridCustomers").data("kendoGrid");
    var dataSource = grid.dataSource;
    var currentColumnState = new Array();
 
    for (var i = 0; i < grid.columns.length; i++) {
 
        if (grid.columns[i].hidden == undefined) {
            grid.columns[i].hidden = false;
            currentColumnState.push({
                field: grid.columns[i].field,
                hidden: grid.columns[i].hidden
            });
        }
        else {
            currentColumnState.push({
                field: grid.columns[i].field,
                hidden: grid.columns[i].hidden
            });
        }
    }
 
    var state = {
        page: dataSource.page(),
        pageSize: dataSource.pageSize(),
        sort: dataSource.sort(),
        group: dataSource.group(),
        filter: dataSource.filter(),
        columns: currentColumnState
    };
 
    return JSON.stringify(state);
}

Load State

function SetDataGrid(data) {
            debugger;
            var result = data.result;
            var jsonResult = $.parseJSON(result);
 
            var state = $.parseJSON(jsonResult.Data);
 
            var grid = $("#GridCustomers").data("kendoGrid");
            var options = grid.options;
 
            for (var i = 0; i < state.columns.length; i++) {
                options.columns[i].hidden = state.columns[i].hidden;
                console.log(state.columns[i]);
                if (state.columns[i].hidden == true) {
                    grid.hideColumn(i);
                }
                else {
                    grid.showColumn(i);
                }
            }
 
            options.columns = state.columns;
            options.dataSource.page = state.page;
            options.dataSource.pageSize = state.pageSize;
            options.dataSource.sort = state.sort;
            options.dataSource.filter = state.filter;
            options.dataSource.group = state.group;
 
            grid.destroy();
            $("#GridCustomers").kendoGrid(options);
        }
 

 

Thanks All

Dimitar
Telerik team
 answered on 22 Sep 2016
1 answer
203 views

This works:

.Read(read => read.Action("StandardTableReadNull", "DashDataparts", new { AdditionalParam = "foo" })

This doesn't:

 

 

.Read(read => read.Action("StandardTableReadNull", "DashDataparts").Data("additionalData")
<script>
    function additionalData() {
        return {
            AdditionalParam: "foo"
        }
    }
</script>

In the second example, the script never hit, so the parameter never got populated in our controller.  (In both cases, our Read controller action was hit, but the "AdditionalParam" parameter was only populated in the first example)

We tried putting the script in our main js file, putting it on our view page, and putting it directly inline in the .Data call, none of which worked.

Any thoughts why?  Any help would be greatly appreciated! :)

 

 

Eyup
Telerik team
 answered on 22 Sep 2016
9 answers
1.6K+ views
Hi,
My goal is to save the grid settings (filter, sort, group,page, pagesize) in a cache or in a database and restore it.
I am able to save the grid setting but not able to apply it back. 
I save the grid setting on grid databound call

var grid = $("#DocumentGrid").data().kendoGrid;
var dataSource = grid.dataSource;

var state = {
                page: dataSource.page(),
                pageSize: dataSource.pageSize(),
                sort: dataSource.sort(),
                group: dataSource.group(),
                filter: dataSource.filter()
            };

            $.ajax(
                 "/controller/SaveGridSettings", {
                     data: dataSource.transport.parameterMap(state, "read")
                 });
In the controller, i am saving it in a dictionary where "string" is a GUID and saving the setting as a Kendo.Mvc.UI.DataSourceRequest

Dictionary<string, Kendo.Mvc.UI.DataSourceRequest>

For testing purpose, i created a button click event to apply the settings.
To read the grid setting and apply it, i tried the following and it didn't work
var grid = $("#DocumentGrid").data().kendoGrid;
        var dataSource = grid.dataSource;
        $.get("/controller/GetGridSettings", {
            Id:  id <-- Passed in during the call
        }).done(function (data) {
                         dataSource.query(data);
                      //dataSource.filter(data.Filters);  <-- Also tried this way
                     //dataSource.sort(data.Sorts);
        });
I want to apply the saved setting when the users navigate to different page and come back to the page with the grid and when they log out and log back in.

Any help is appreciated.

Thanks,
Dinesh
Terry
Top achievements
Rank 1
 answered on 21 Sep 2016
5 answers
136 views

Hi,

 

is there a way (like in PivotGrid for ASP.NET AJAX) to persist a pivot grid on the server.

Usage: the user drags columns around till he has the desired result - with save he can persist this "view" on the server. Later he can recall this "view" to have the same PivotGrid configuration again.

 

Manfred

Viktor Tachev
Telerik team
 answered on 21 Sep 2016
4 answers
143 views

Hey Guys

 

Just busy adding custom validation to my solution and came across this issue.

I used the example of adding custom validation for Dates provided here  and change it to support time between and using TimeSpans.

Please ignore how crappy the coding is, I am not a javascript coder, so I just bash my way through it! 

IsTimeBetween: function (input) {
                        if (input.is("[data-val-IsTimeBetween]") && input.val() != "") {
                            var fromtime =input.val();
                            var fromtimeAr = fromtime.split(":");
                            var fromtimeMin = 0;
                            fromtimeMin = fromtimeMin + parseInt(fromtimeAr[1]);
                            fromtimeMin = fromtimeMin + parseInt(fromtimeAr[0] * 60);
                            console.log('validating between');
                             
                            var lowertime = $("[name='" + input.attr("data-val-IsTimeBetween-lowerproperty") + "']").val();
                            var lowertimeAr = lowertime.split(":");
                            var lowertimeMin = 0;
                            lowertimeMin = lowertimeMin + parseInt(lowertimeAr[1]);
                            lowertimeMin = lowertimeMin + parseInt(lowertimeAr[0] * 60);
                             
                            var uppertime = $("[name='" + input.attr("data-val-IsTimeBetween-upperproperty") + "']").val();
                            var uppertimeAr = uppertime.split(":");
                            var uppertimeMin = 0;
                            uppertimeMin = uppertimeMin + parseInt(uppertimeAr[1]);
                            uppertimeMin = uppertimeMin + parseInt(uppertimeAr[0] * 60);
                             
                            return !fromtime || !lowertime || !uppertime || (fromtimeMin > lowertimeMin && fromtimeMin < uppertimeMin);
                        }
                        return true;
                    }     

Maria Ilieva
Telerik team
 answered on 21 Sep 2016
1 answer
300 views

Hi

 

Let me paint the picture. I am trying to build an application for the medical domain. Basically creating accounts which are responsible for paying the account. Then dependants linked to an account. And each account has transactions linked to it. That is the basic domain. I am trying to display a grid showing the account information. My architecture is as follows. Using entity framework 6 as my ORM. I have built some DTO's inside a model project that hold all my models which I intend to carry over the wire. I have a seperate asp mvc api project which will act as my data hub for different types of front ends, browser or mobile. At the moment I'm trying to build a front end using MVC 5 using the telerik kendo ui controls to make the ui nice. I'm struggling even after reading various articles on trying to achieve this. I have a method in my web api project which returns a list of accounts which I pasted below. After reading some new articles I've realised that it be better to refactor this method to return the kendo DataSourceResult and accept the modelbinder as a parameter. My question is. How do I pass the practiceid parameter into this method so that it only returns me a list of accounts that belong to the practice the user has logged into. I have also pasted my grid definition below.

[Route("api/Accounts")]public HttpResponseMessage GetAccountsByPractice(int practiceId){     IAccountRepository accountRepository = new AccountRepository("");     try     {         var results = accountRepository.GetAccountsByPractice(new Practice { PracticeId = practiceId });         return Request.CreateResponse(HttpStatusCode.OK, results);     }     catch (Exception)     {         throw;     }}

 

@(Html.Kendo().Grid<Medistat.MedistatWeb.Domain.Model.AccountDTO>()       .Name("accountGrid")       .Columns(columns =>       {           columns.Bound(p => p.AccountNumber);           columns.Bound(p => p.AccountHolderName).Width(100);           columns.Bound(p => p.IdNumber).Width(100);           columns.Bound(p => p.MedicalAidName).Width(100);           columns.Bound(p => p.MedicalAidNumber).Width(100);       })       .ToolBar(tools =>       {           tools.Create();       })       .Sortable()       .Pageable()       .Filterable()       .DataSource(dataSource =>           dataSource             .WebApi()             .Model(model =>             {                 model.Id(p => p.AccountId);             })             .Events(events => events.Error("error_handler"))             .Read(read => read.Url("http://localhost:54510/api/accounts"))             .Create(create => create.Url("http://localhost:54510/api/accounts"))       ))

 

Viktor Tachev
Telerik team
 answered on 21 Sep 2016
1 answer
524 views

Hi,

Based on the demo in http://demos.telerik.com/aspnet-mvc/dialog/treeview-integration. i am trying to achieve a filter in the treelist control. But the data i am binding in the treelist has about 5000 records, hence the filtering takes about 7 seconds, please advise if the code provided in the demo is suitable for this scenario or do i need to use a different approach.

Also i am using the selected property of the item to decide on the selection in the treelist, and setting the selected item text to a textbox, if i change the textbox would want to unselect the selected item in the treelist, is this possible.

@Html.Kendo().TextBoxFor(t => t.Name).Name("LocationName")<button id="ShowAll" class="k-button AllLoad" onclick="ShowAll();">Show all</button>
<div class="dropdowndiv" id="divLocationId" style="display:none; overflow:auto; text-align: left; z-index:999999; position:absolute;background-color:white;border:1px solid #c3d9f9;width:488px;padding-left:2px" onblur="hideAll();">
          
   @(Html.Kendo().TreeView().Name("TreeViewDropDown")
    .AutoBind(false).Events(ev => ev.DataBound("treeViewDataBound"))
    .DataTextField("text")
   .BindTo(Model.LocationList).Events(e=>e.Select("onSelection"))
    )
</div >
 
<script>
    $(document).ready(function () {
        $("#LocationName").on("input", function () {
            $('#divLocationId').slideDown(200);
            var query = this.value.toLowerCase();
            var dataSource = $("#TreeViewDropDown").data("kendoTreeView").dataSource;
            filter(dataSource, query);
            matchColors(query);
        });
    });
 
    function onSelection(e)
    {
        if (e.node.childElementCount > 1) {
            e.preventDefault();
            return;
        }
        $("#LocationName").val(e.node.innerText);
        $("#locationId").val(e.node.innerText);
    }
 
    function ShowAll()
    {
        $('#divLocationId').slideDown(200);
        var dataSource = $("#TreeViewDropDown").data("kendoTreeView").dataSource;
        filter(dataSource, "");
    }
 
     function treeViewDataBound(e) {
        e.sender.expand(e.node);
    }
 
    function filter(dataSource, query) {
        var hasVisibleChildren = false;
        var data = dataSource instanceof kendo.data.HierarchicalDataSource && dataSource.data();
 
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            var text = item.text.toLowerCase();
            var itemVisible =
                query === true // parent already matches
                || query === "" // query is empty
                || text.indexOf(query) >= 0; // item text matches query
 
            var anyVisibleChildren = filter(item.children, itemVisible || query); // pass true if parent matches
 
            hasVisibleChildren = hasVisibleChildren || anyVisibleChildren || itemVisible;
 
            item.hidden = !itemVisible && !anyVisibleChildren;
        }
 
        if (data) {
            // re-apply filter on children
            dataSource.filter({ field: "hidden", operator: "neq", value: true });
        }
 
        return hasVisibleChildren;
    }
 
    function matchColors(query, element) {
        $("#TreeViewDropDown .k-in:containsIgnoreCase('" + query + "')").each(function () {
            var index = $(this).html().toLowerCase().indexOf(query.toLowerCase());
            var length = query.length;
            var original = $(this).html().substr(index, length);
            var newText = $(this).html().replace(original, "<span class='query-match'>" + original + "</span>");
            $(this).html(newText);
        });
    }
 
    $.expr[':'].containsIgnoreCase = function (n, i, m) {
        return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
    };
 
    function hideAll() {
        $('#divLocationId').slideUp('fast');
    }
    $(document).ready(function () {
        var grid = $("#Feedback").data("kendoGrid");
        if (grid != undefined || grid != null)
            DisplayNavigationMessage("Feedback");
        grid = $("#FeedbackQuestions").data("kendoGrid");
        if (grid != undefined || grid != null)
            DisplayNavigationMessage("FeedbackQuestions");
    });
    $("body").click(function (e) {
        if (e.target.className != "dropdowndiv" && e.target.className != "k-icon k-i-expand" &&
            e.target.className != "k-icon k-i-collapse" && e.target.className != "k-button AllLoad")
        {
            hideAll();
        }
    });
</script>

 

Konstantin Dikov
Telerik team
 answered on 21 Sep 2016
3 answers
362 views

I am new to the "MVC" world so I expect that I am doing something wrong.  I am constantly moving between a desktop station and a laptop.  Projects created on one system will not load successfully from Team Foundation Services on the second system.  Both computers have are fully licensed and have all the same levels of .NET and other tools installed.  Both are kept "current" from the "Telerik" and "Microsoft" perspective.

The problem seems to be related to the "Kendo.Mvc.dll".  The computer knows where it is and links and compiles perfectly fine on machine #1.  When I save all to TFS then move to workstation #2 the problems occur.  A complete get of all source code, and subsequent compilation, shows that the computer cannot find "Kendo.Mvc.dll".  The reference shows a small symbol indicating its reference is invalid.  I am forced to manually remove the .DLL, then browse for the .DLL.  This solves the immediate problem however it then reoccurs when I do the reverse (move back to machine #1).  All Telerik/Kendo .DLL's are set to "copy local".

A possible symptom of the problem:  A "upgrade" action causes the upgrade wizard to crash.  It dies reporting that it cannot find the .DLL despite it being present in the respective folders.  If it is of concern, the projects are targeted at .NET Framework 4.6.1.  I appear to be using MVC 5.

Is anyone else having similar issues?  What am I doing wrong?  While this is in no way a showstopper, it is an annoyance I would like to resolve.

Vessy
Telerik team
 answered on 21 Sep 2016
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
Rating
ScrollView
ButtonGroup
CheckBoxGroup
NavBar
ProgressBar
QRCode
RadioButton
Scroller
Timeline
TreeMap
TaskBoard
OrgChart
Captcha
ActionSheet
Signature
DateTimePicker
AppBar
BottomNavigation
Card
FloatingActionButton
Licensing
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
Rob
Top achievements
Rank 3
Bronze
Iron
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Bronze
Iron
Iron
Sergii
Top achievements
Rank 1
Iron
Iron
Dedalus
Top achievements
Rank 1
Iron
Iron
Lan
Top achievements
Rank 1
Iron
Doug
Top achievements
Rank 1
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?