Telerik Forums
UI for ASP.NET MVC Forum
8 answers
487 views

Hello!

 

First of all I'm posting tihs in the DropDownTree section but I'm not convinced that the DropDownTree is necessarily the right component for what I want.

Basically I need to display something exactly like the autocomplete component but it must have a hierarchy, so the items displayed in this "autocomplete" can be a parent item or a child item and each child is linked to a parent and should be somehow intended. This looks like what the DropDownTree offers but I'm having several problems working with it.

 

In order to get my data, I need to call an external service which takes two parameters, the language and the search string (which should be whatever the user typed in the autocomplete box).

This is how I setup my DropDown:

01.@(Html.Kendo().DropDownTree()
02.  .Name("search")
03.  //.DataTextField("name")
04.  .Placeholder("Search")
05.  .Filter(FilterType.Contains)
06.  .MinLength(2)
07.  .DataSource(dataSource => dataSource
08.    .Read(read => read
09.      .Action("Search", "Blabla", new { culture = Localizer.CultureName })
10.      .Data("onAdditionalData")
11.    )
12.  )
13.)
14.<input type="hidden" id="searchFilter" name="searchFilter" />

 

In onAdditionalData, I setup the two parameters that my Search action from the Blabla controller requires:

1.<script>
2.    function onAdditionalData() {
3.        return {
4.            language: "@Localizer.CultureName",
5.            searchString: $("#searchFilter").val()
6.        };
7.    }
8.</script>

Since I didn't find an easy way to get the value that the user typed, I'm binding the filtering event like this and setting the value in a hidden field, which is then used by onAdditionalData to pass the search string:

01.function dropdowntree_filtering(e) {
02.    //get filter descriptor
03.    var filter = e.filter;
04.    $("#searchFilter").val(filter.value);
05.}
06.
07.$(function () {
08.    $(document).ready(function() {
09.        var dropdowntree = $("#search").data("kendoDropDownTree");
10.        dropdowntree.bind("filtering", dropdowntree_filtering);
11.    });
12.});

 

Then my controller calls the service with the 2 parameters and that's fine, I get my results in essentially this format:

01.[
02.  {
03.    "id":851,
04.    "name":"Some name 1",
05.    "idParent":null,
06.    "children":[
07. 
08.    ]
09.  },
10.  {
11.    "id":402,
12.    "name":"Some name 2",
13.    "idParent":null,
14.    "children":[
15.      {
16.        "id":403,
17.        "name":"Some name 3",
18.        "idParent":402,
19.        "children":null
20.      },
21.      {
22.        "id":404,
23.        "name":"Some name 4",
24.        "idParent":402,
25.        "children":null
26.      }
27.    ]
28.  },
29.  {
30.    "id":923,
31.    "name":"Some name 5",
32.    "idParent":null,
33.    "children":[
34.      {
35.        "id":929,
36.        "name":"Some name 6",
37.        "idParent":923,
38.        "children":null
39.      }
40.    ]
41.  },
42.  {
43.    "id":728,
44.    "name":"Some name 7",
45.    "idParent":727,
46.    "children":[
47.      {
48.        "id":734,
49.        "name":"Some name 8",
50.        "idParent":728,
51.        "children":null
52.      }
53.    ]
54.  },
55.  {
56.    "id":757,
57.    "name":"Some name 9",
58.    "idParent":727,
59.    "children":[
60.      {
61.        "id":763,
62.        "name":"Some name 10",
63.        "idParent":757,
64.        "children":null
65.      }
66.    ]
67.  },
68.  {
69.    "id":405,
70.    "name":"Some name 11",
71.    "idParent":null,
72.    "children":[
73.      {
74.        "id":406,
75.        "name":"Some name 12",
76.        "idParent":405,
77.        "children":null
78.      }
79.    ]
80.  }
81.]

 

Now my problem is that I don't know how to build a result set that the dropdowntree can display properly. I've tried to build a list of DropDownTreeItem like this:

01.public async Task<JsonResult> Search(string language, string searchString)
02.{
03.  IReadOnlyCollection<MyDto> results = await _myService.Search(language, searchString);
04.  IList<DropDownTreeItem> items = new List<DropDownTreeItem>();
05.  foreach(var r in results)
06.  {
07.    DropDownTreeItem item = new DropDownTreeItem
08.    {
09.      Id = r.Id?.ToString(),
10.      Text = r.Name,
11.      HasChildren = r.Children.Count > 0
12.    };
13.    if(r.Children.Count > 0)
14.    {
15.      foreach(var c in r.Children)
16.      {
17.        item.Items.Add(new DropDownTreeItem
18.        {
19.          Id = c.Id?.ToString(),
20.          Text = c.Name,
21.          HasChildren = false
22.        });
23.      }
24.    }
25.    items.Add(item);
26.  }
27.  return Json(items);
28.}

 

But that doesn't really work, the autocomplete does not contain any items then, for some reason that also doesn't populate anything in the autocomplete (I get "no data found" even though there are items). From the examples I've seen, it seems that DropDownTreeItem needs to call the search method recursively to get its children and this doesn't work for me because my service already returns me all the relevant children based on my search string.

I've tried using the ToTreeDataSourceResult method like this:

1.public async Task<JsonResult> Search(string language, string searchString)
2.{
3.  IReadOnlyCollection<MyDto> results = await _myService.Search(language, searchString);
4.  var tree = results.ToTreeDataSourceResult(new DataSourceRequest(), a => a.Id, a => a.IdParent);
5.  return Json(tree.Data);
6.}

 

that also doesn't populate anything in the autocomplete. (I get "no data found" even though the tree.Data has data).

 

I'm starting to think that this DropDownTree is not the right component and maybe I can achieve what I want with a simple AutoComplete and some styling ?

Hopefully my problem is clear enough with those details.

Any help would be greatly appreciated,

Thanks!

 

 

Ivan Danchev
Telerik team
 answered on 14 Nov 2019
12 answers
1.2K+ views

Hi All,

I have razor page that gets data source on server side from "public async Task OnGetAsync()". I was able to get data from api and have it set to List successfully. Now, how can I set this datasource to my Kendo Grid? Thanks in Advance!

@(Html.Kendo().Grid<UserList>().Name("grid")
  .Groupable()
  .Sortable()
  .Editable()
  .Scrollable()
  .ToolBar(x => x.Excel())
  .Columns(columns =>
  {

  columns.Bound(column => column.Id); 

  columns.Bound(column => column.firstName);
  columns.Bound(column => column.lastName);
  columns.Command(column =>
  {
  column.Edit();
  column.Destroy();
  });
  })
  .Excel(excel => excel
  .FileName("Export.xlsx")
  .Filterable(true)
  .ProxyURL("/Admin?handler=Save")
   )
  .DataSource(ds => ????
  .PageSize(10)
   )
  .Pageable()
)
Ryan
Top achievements
Rank 1
 answered on 14 Nov 2019
1 answer
679 views
Hello,

We have a Grid in which one of the fields - CategoryId - is a foreign key. Using the normal .ForeignKey(…) method works but it is not enough for this particular situation as the data do be displayed inside has a hierarchy to it.

We are trying to, by means of a custom editor template, display that field as a DropDownTree.


The contents of the DropDownTree are also dependant on another foreign key - SchemeId - which is filtered inside the editor template's DataSource.Read method.

All of this works in terms of actually selecting the item in the DropDownTree - however the value is not stored / or is just stored on certain situations. i.e, as you select other column this one remains blank (no red triangle on corner).


I should also point out that we are using the Grid in "InCell" edit mode and have the .Batch mode set to true (event though the same happens if it's not in Batch mode).


I have tried many things, including tapping on to certain events and setting the dirty fileds property in the grid's data but with no success (also not sure if I should be meddling with it).



How should we go about doing this?


To make things more clear,  here are the contents of the files in question:



Contents of Views\Items\List.cshtml
 
@using Project.Web.Models
@model ItemListViewModel
@(Html.Kendo()
    .Grid<ListItem>(Model.Items)
    .Name("itemsGrid")
    .Columns(columns =>
    {
        columns.ForeignKey(i => i.SchemeId, Model.SchemesList, "Value", "Text").Filterable(ftb => ftb.Multi(true).Search(true));
        columns.ForeignKey(i => i.CategoryId, Model.Categories, "CategoryId", "Name")
            .EditorViewData(new { Categories = Model.Categories })
            .EditorTemplateName("CategoryDropdown").Filterable(ftb => ftb.Multi(true).Search(true));
        columns.Bound(i => i.Value);
        columns.Bound(i => i.Date).Title("Date").Format("{0:MM/yyyy}").Sortable(true).EditorTemplateName("CustomMonthPicker").Filterable(ftb => ftb.Multi(true).Search(true));
        columns.Command(command => { command.Destroy(); });
    })
    .ToolBar(toolbar => { toolbar.Create(); toolbar.Save(); })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .DataSource(dataSource =>
        dataSource.Ajax()
        .Batch(true)
        .Model(model =>
        {
            model.Id(a => a.Key);
        })
        .Create(create => create.Action("SaveItems", "AssetData"))
        .Read(read => read.Action("ReadItems", "AssetData"))
        .Update(update => update.Action("SaveItems", "AssetData"))
        .Destroy(destroy => destroy.Action("DeleteItems", "AssetData"))
    )
)
<script>
    function filterCategories() {
        var grid = $("#itemsGrid").data("kendoGrid");
        
        var dataItem = grid.dataItem(grid.tbody.find("tr:has(.k-edit-cell)"));
        return {
            schemeId: dataItem.SchemeId
        };
    }
</script>
 


-----


Contents of Views\Shared\EditorTemplates\CategoryDropdown.cshtml 


@using Kendo.Mvc.UI;
@model object
@(Html.Kendo().DropDownTreeFor(m => m)
    .ValuePrimitive(true)
    .Filter("contains")
    .DataTextField("Text")
    .DataValueField("Value")
    .DataSource(dataSource =>
    {
        dataSource.Model(m => m.HasChildren("HasChildren").Children("Items"));
        dataSource.Read(read => read.Action("GetSchemeCategories", "Category").Data("filterCategories"));
    })
)
 


----


Thanks!
Alex Hajigeorgieva
Telerik team
 answered on 14 Nov 2019
5 answers
2.2K+ views

I have an MVC grid with inline editing set and the user is able to select an entire row. I've managed to change the hover background color of a non-selected row by changing some CSS. When the user selects a row I'm also able to change the background color of the selected row. However, what I cannot seem to change is the hover color of the selected row. It's a deep blue and I'm unable to change it. 

This is the CSS code I've created:

.k-grid .k-state-selected {<br>    background-color: #C4FAEC;<br>    color: #000000;<br>}<br>

 

.k-grid .k-state-selected:hover {<br>    background-color: #C4FAEC;<br>    color: #000000;<br>}<br>

 

.k-grid td.k-state-selected:hover, .k-grid tr:hover {<br>    color: #000000;<br>    background-color: #C4FAEC;<br>}<br>

 

Randy
Top achievements
Rank 1
 answered on 13 Nov 2019
1 answer
943 views

Hi.

I'd like to display a checkbox with a label that contains HTML.

 

For example:

 

Model:

 

[Display(Name = "I agree to the <a href=\"{0}\">Terms and Conditions</a>")]

public bool IAgreeToTheTermsAndConditions { get; set; }

 

View:

 

@Html.Kendo().CheckBoxFor(model => model.IAgreeToTheTermsAndConditions).Label(

                            string.Format(

                                Html.DisplayNameFor(model2 => model2.IAgreeToTheTermsAndConditions).ToString(),                                 @Url.Action("TermsAndConditions", null)))

 

However, the label is rendered with the HTML encoded:

I have agree to the &amp;lt;a href=&amp;quot;/TermsAndConditions&amp;quot;&amp;gt;Terms and Conditions&amp;lt;/a&amp;gt;

 

How can I pass raw HTML to the Label?

 

Thank you.

Nikolay
Telerik team
 answered on 12 Nov 2019
6 answers
1.1K+ views

When i am follow the guide for show the pdf file, i am getting the error 'Cannot read property 'GlobalWorkerOptions' of undefined' ..

 

Am i missing some stuff in the code, to make it work?

 

Vladimir
Top achievements
Rank 1
 answered on 12 Nov 2019
9 answers
1.9K+ views

Hi.

The problem is about sorting.

It does not create a query by my own method.

I want to understand why. Because it doesn't make sense to me. This is very easy sample;

var db = new TicketSystemEntities();
var issues = (from a in db.testTable
                    //orderby a.name ascending
              select new
              {
                  a.name,
                  a.guid,
              }).OrderByDescending(f => f.name);
//issues = issues.OrderByDescending(k => k.name);
return Json(Test().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);

 

Three ordering types not ordering.. Sql profiling result is;

ORDER BY row_number() OVER (ORDER BY [xxxx].[name] ASC)

 

So.. OrderByDescending not used.. When i change order of fields;

a.guid,
a.name,

 

Profiling is changing like this;

ORDER BY row_number() OVER (ORDER BY [xxxx].[guid] ASC)

 

So, system getting first field for ordering with "ASC".. Not "DESC".

When i use Sort property in DataSource in razor, its working;

.DataSource(dataSource => dataSource
  .Ajax()
  .Sort(s=>s.Add(d=>d.name).Descending())
  .Model(model => model.Id(p => p.guid))
  .PageSize(10)
  .Read(read => read.Action("y", "x"))
)

 

When i use AsEnumerable;

db.testTable.OrderBy(o => o.name).AsEnumerable().Select(x => x);

 

its working with AsEnumerable or ToList().

it just doesn't work for the telerik Grid. In dropdown or other telerik modules, iqueryable queries can run sequentially.

I want to do the sorting with the controller.

First time I encounter such a problem.

Is there an explanation for this problem?

Plamen
Telerik team
 answered on 12 Nov 2019
9 answers
998 views

I have a MVC .NET application. I have a dropdown list that does backend calls to populate it. I want to copy the field and everything seems to work properly... except the searching, the search value that is searched for is from the original field and not the field I am entering the search into. I am assuming that I have missed something when copying the field.  

First I copy the field:

var fieldToCopy = currentRow.find("#" + oldFieldId);
fieldToCopy.clone()
       .attr("id", newFieldId)
       .attr("name", newFieldName)
       .appendTo('#' + fieldId);

 

then I get the field I created:

var newField = $(`#${newFieldId}`);
if (!newField.length) return;

 

I then init the new field:

var originalWidgetType = "kendo" + window.kendo.widgetInstance(fieldToCopy).options.name;
var originalWidget = fieldToCopy.data(originalWidgetType);
newField[originalWidgetType](originalWidget.options);

 

This gets me 90% of the way. I have a working dropdown. The only problem is that although I have a cloned field, searching does not work. I always get the search value from the field I copied. 

When I check the HTML I see that the <script> which is in the original code but missing in the cloned code. How do I properly initialise a cloned field?

This is the stuff that is missing after the clone.

kendo.syncReady(function(){jQuery("#Fields_21__Values_0_").kendoDropDownList({"minLength":3,"value":"100015026","filter":"contains","dataSource":{"transport":{"read":{"url":"/d3Search/Shared/Document/TypeAhead?docId=GD00000148\u0026docType=DEPSU\u0026fieldNumber=61\u0026row=0\u0026currentValue=100015026","data":function() { return kendo.ui.DropDownList.requestData(jQuery("#Fields_21__Values_0_")); }},"prefix":""},"serverFiltering":true,"filter":[],"schema":{"errors":"Errors"}}});});

 

Hopefully somebody can help.

 

 

Ursus
Top achievements
Rank 1
Iron
 answered on 12 Nov 2019
2 answers
471 views

I'm making the Grid/Inline editing list using Kendo UI MVC referring this: https://demos.telerik.com/aspnet-mvc/grid/editing-inline 

I was trying to create and update text with HTML tag, for example, <br>, <h> with some other texts.

But whenever I put HTML tags such as those and even like '<b', '<h', it wasn't created or updated.

They're not updated and created like this image below:

Hyewon
Top achievements
Rank 1
 answered on 11 Nov 2019
1 answer
1.3K+ views

Hi,

I'm trying to pass a DateTime value (Start_Date) to an ActionResult used by a template, but seems it is always null (other arguments string and int format are ok), changing type from dateTime to string seems to work, the value is a not null datetime string version but I would like to use directly the datetime, any suggestion?

 

(index.cshtml)

            columns.Bound(p => p.Start_Date).Format("{0:dd/MM/yyyy}");
            columns.Template(@<text></text>).ClientTemplate(
                                    "<a href='" +
                                         Url.Action("Details", "Data_Values") +
                                         "/?ContactID=#=Contact_ID#&SerialNumber=#=Serial_Number#&StartDate=#=Start_Date#'" +
                                    ">Details</a>").Width("100px");

(controller Data_ValuesController)

public ActionResult Details(int? ContactID, DateTime? StartDate, String SerialNumber)
        {

[...]

 

Veselin Tsvetanov
Telerik team
 answered on 11 Nov 2019
Narrow your results
Selected tags
Tags
Grid
General Discussions
Scheduler
DropDownList
Chart
Editor
TreeView
DatePicker
ComboBox
Upload
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
Dialog
MultiColumnComboBox
DropDownTree
Checkbox
Slider
Switch
Notification
Accessibility
ListView (Mobile)
Pager
Security
ColorPicker
DateRangePicker
Wizard
Styling
Chat
DateInput
MediaPlayer
TileLayout
Drawer
SplitView
Template
Barcode
ButtonGroup (Mobile)
Drawer (Mobile)
ImageEditor
RadioGroup
Sparkline
Stepper
TabStrip (Mobile)
GridLayout
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
SmartPasteButton
PromptBox
SegmentedControl
LLM Kit
+? more
Top users last month
Simon
Top achievements
Rank 2
Iron
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Marco
Top achievements
Rank 4
Iron
Iron
Iron
Grant
Top achievements
Rank 3
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Simon
Top achievements
Rank 2
Iron
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Marco
Top achievements
Rank 4
Iron
Iron
Iron
Grant
Top achievements
Rank 3
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?