Telerik Forums
UI for ASP.NET MVC Forum
0 answers
90 views

Hi everyone,

I'm in the process of developing an ASP.NET MVC application that should provide the ability to record the time worked by an employee with a chart.
I use the Telerik UI Scheduler for this. The integration and use in general works perfectly, but the EditorTemplate gives me problems. (see code)
As you can see, I'm trying to open data from a database in a DropDown using "ViewData" within the EditorTemplate. In the index function (ActionResult) in the controller I have declared the "ViewData", which gets the data from the database via a service.

Now the problem: If I want to use the "ViewData", the EditorTemplate can no longer be built. (See error in browser console -> pic in attachement)
If I use this ViewData in a PartialView it works without problems.
However, if I comment out this part in the controller (from "var projects..." to "...ToList();") and leave the EditorTemplate the same, everything works again and I can open the EditorTemplate via double-click on the scheduler. But I still can't get the data.

What do I have to do so that I can use the data from the "ViewData" in the EditorTemplate?
I hope someone can help me.

 

Controller: (TimeTrackingController.cs)

public async Task<ActionResult> Index() //TODO: ActionResult
        {
            // ignore this below ----------------------------------------------
            var overview = new ActivityOverviewModel();

            overview.PaList = new List<PA>
            {
                new PA
                {
                    Id = 1,
                    Number = 201885445,
                    PaName = "Inbetriebnahme",
                    OrderNumber = 201745965,
                    OrderName = "Ein sehr schwieriger Auftrag",
                    ProjectNumber = 2019788458,
                    ProjectName = "Laser für Gießerei programmieren",
                    CompanyName = "Constellium Rolled Products",
                    PlannedHours = 70,
                    CurrentHours = 80,
                    PaLeft = false,
                    TechnicallyReady = true,
                    Favorite = false
                },
                new PA
                {
                    Id = 1,
                    Number = 201888874,
                    PaName = "Lösungsfindung",
                    OrderNumber = 2197811144,
                    OrderName = "Ein sehr schwieriger zweiter Auftrag",
                    ProjectNumber = 2019788458,
                    ProjectName = "Laser für Eingang programmieren",
                    CompanyName = "S&K Anlagentechnik",
                    PlannedHours = 70,
                    CurrentHours = 45,
                    PaLeft = false,
                    TechnicallyReady = false,
                    Favorite = false
                }
            };
            // ignore this above ----------------------------------------------

            var projects = await _projectService.GetProjectsForTimelineCreateAsync();

            ViewData["ActiveProjects"] = projects.Select(p => new TimelineCreateProjectModel
            {
                ProjectId = p.ProjectId,
                ProjectInfo = $"{p.ProjectNumber} - {p.ProjectName}"
            }).OrderByDescending(p => p.ProjectInfo).ToList();

            return View(overview);
        }

 

Index.cshtml:

<div id="right">
        @(Html.Kendo().Scheduler<ActivityModel>()
                    .Name("ActivityScheduler")
                    .Editable(e => e.TemplateName("EditActivity"))
                    //.StartTime(new DateTime(2022, 01, 1, 5, 00, 00)) // scheduler starts at 5 am
                    .DataSource(d => d
                    .Read(r => r.Action("ActivityCalendarRead", "TimeTracking", new { area = "Sktcrm" }))
                    .ServerOperation(true))
                    .Views(v =>
                    {
                        v.DayView();
                        v.WeekView(view => view.Selected(true));
                        v.MonthView();
                    })
                    .Events(ev =>
                    {
                        ev.Edit("tripChanged");
                        ev.Add("tripChanged");
                        ev.DataBound("checkHolidays");
                        ev.DataBinding("navigate");
                    })
                    .Editable(e => e.Window(w => w.Title("Aktivität bearbeiten")))
        )

    </div>

EditorTemplate: (EditActivity.cshtml)

<div>
            @(Html.Kendo().DropDownList()
                .Name("project")
                /*.BindTo(new List<string>()
                {
                    "Test ",
                    "Projekt 123",
                    "Leer",
                    "Test 2"
                })*/
                .ValuePrimitive(true)
                .OptionLabel("Projekt wählen...")
                .DataValueField("ProjectId")
                .DataTextField("ProjectInfo")
                .BindTo((IEnumerable) ViewData["ActiveProjects"]) // TODO: doesnt work!!!
                .Filter(FilterType.Contains)
                .HtmlAttributes(new {@class = "kendoSelectMain"}))
        </div>

 

Thanks in advance
Lars

Lars1603
Top achievements
Rank 1
Iron
 asked on 28 Mar 2022
1 answer
367 views

Hi,

I'm grouping a dropdown and I'm a little puzzled by the display.

My groups are either "Permanent" or "Temporary"

Temporary shows up quite neatly in corner, Permanent appears as an option that can't be selected and is confusing my users.  Can it show the same for both?


        @(Html.Kendo().DropDownList()
            .Name("addevent-type-dropdown")
            .OptionLabel("Select event type...")
            .DataTextField("EventTypeName")
            .DataValueField("EventTypeId")
            .DataSource(source => source
              .Custom()
              .Group(g => g.Add("ChangeType", typeof(string)))
              .Transport(transport => transport
                .Read(read =>
                {
                    read.Action("GetEventTypesDropDown", "Schedule");
                })))
            .HtmlAttributes(new
            {
                style = "width: 600px",
                data_toggle = "tooltip",
                title = "Select event type"
            })
            .Events(e => e.Change("eventTypeChange"))
        )

Thanks

Ivan Danchev
Telerik team
 answered on 21 Mar 2022
1 answer
157 views

I've read the examples, and I've followed along as best as I can, but I'm still having an issue getting a simple dropdown into my grid (ASP.NET MVC)

I have a model called Supplier, and a model called VehicleType

    

public class Supplier { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Display(Name = "Id")] public int SupplierId { get; set; } [Display(Name = "Supplier Number")] public int SupplierNumber { get; set; } [Display(Name = "Name")] public string SupplierName { get; set; } [Display(Name = "Vehicle Type Id")] public int VehicleTypeId { get; set; } [Display(Name = "Status Id")] public int StatusId { get; set; }

// I added this [NotMapped] [UIHint("VehicleType")] public VehicleType VehicleType { get; set; } } public class VehicleType { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int VehicleTypeId { get; set; } public string VehicleTypeName { get; set; } }

My Grid is as follows:

@(Html.Kendo().Grid<MyProject.Models.Schedule.Supplier>
    ()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Select().Width(50);
        columns.Bound(p => p.SupplierNumber).Filterable(ftb => ftb.Multi(true));
        columns.Bound(p => p.SupplierName).Groupable(true).Filterable(ftb => ftb.Multi(true));
        //columns.Bound(p => p.VehicleTypeId).Filterable(ftb => ftb.Multi(true));
        columns.Bound(p => p.VehicleType).ClientTemplate("#=VehicleType.VehicleTypeName#").Sortable(false);

    })
    .Pageable()
    .Sortable()
    .ToolBar(toolBar =>
    {
        toolBar.Create();
        toolBar.Save();
    })
    .Editable(editable => editable.Mode(GridEditMode.InCell))
    .PersistSelection()
    .Scrollable()
    .Groupable()
    .Filterable()
    .HtmlAttributes(new { style = "height:600px;" })
    .Resizable(r => r.Columns(true))
    .DataSource(dataSource => dataSource
        .Ajax()
        .Model(model => model.Id(p => p.SupplierId))
        .PageSize(100)
        .Events(events => events.Error("error_handler"))
        .Read(read => read.Action("GetSuppliers", "Schedule"))
        .Update(update => update.Action("EditSupplier", "Schedule"))
        .Create(create => create.Action("CreateSupplier", "Schedule"))
    )
    )

My controller looks like this:

        // View for the page
        public ActionResult Supplier()
        {
            ViewData["vehicleTypes"] = new Models.MyContext()
                .vehicleTypes
                .Select(v => new VehicleType
                {
                    VehicleTypeId = v.VehicleTypeId,
                    VehicleTypeName = v.VehicleTypeName
                })
                .OrderBy(v => v.VehicleTypeName);

            return View();
        }

        // Using this to get the data for the grid
        public ActionResult GetSuppliers([DataSourceRequest] DataSourceRequest request)
        {
            List<Models.Schedule.Supplier> result = MyLogic.suppliers();
            return Json(result.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
        }

And finally I created an EditorTemplate called VehicleType.cshtml

@(Html.Kendo().DropDownList()
        .Name("VehicleType") 
        .DataValueField("VehicleTypeId")
        .DataTextField("VehicleTypeName")
        .BindTo((System.Collections.IEnumerable)ViewData["vehicleTypes"])
    )

When I try to view the grid I get this error:

The entity or complex type 'MyProject.Models.VehicleType' cannot be constructed in a LINQ to Entities query.

After some googling, I changed my ViewData lookup in my controller to this:

Which displays my grid (empty though there should be 31 rows) and the console has the following error:

Uncaught TypeError: Cannot read properties of null (reading 'VehicleTypeName')
    at eval (eval at compile (kendo.all.js:241:30), <anonymous>:3:3673)
    at init._rowsHtml (kendo.all.js:74650:37)
    at init._renderContent (kendo.all.js:75513:34)
    at init.refresh (kendo.all.js:75329:22)
    at init.d (jquery.min.js:2:3873)
    at init.trigger (kendo.all.js:171:37)
    at init._process (kendo.all.js:8341:22)
    at init.success (kendo.all.js:8037:22)
    at success (kendo.all.js:7928:42)
    at Object.n.success (kendo.all.js:6762:25)

Can someone point me in the right direction here? 

Without trying to add the dropdown, it all works as expected, but I'd rather not have to type in the id values when editing/creating a row

I've been bashing my head against the wall for it for a couple of hours now, so any kind of help would be greatly appreciated.

Thanks

 

Anton Mironov
Telerik team
 answered on 22 Feb 2022
12 answers
4.5K+ views

Hi,

I have a Kendo DropDownList as follow:

                 Html.Kendo().DropDownList()
                .Name("ddl_" + filter.ReportProcedureId.ToString())
                .Items(i => i.Add().Text(filter.DefaultValue).Value(filter.DefaultValue))
                .SelectedIndex(0)
                .HtmlAttributes(new
                {
                    style = "display:none;"
                })
                .Events(e => e
                    .DataBound("onDropDownBinding")).Render();  

 In the old Telerik MVC extension it is done in onDropDownBinding() like

    function onDropDownBinding(e)
    {
        var isValid = true;
        var reportProcedureId = e.currentTarget.id.replace('ddl_', '');

        ......

    }
Now I want to do it in Kendo. How to do it? Thanks.


Kiran
Top achievements
Rank 1
Veteran
Iron
 answered on 05 Feb 2022
1 answer
239 views

Today I upgraded one of our web apps to the latest version of UI for ASP.NET MVC and since then the DropDownList component doesn't appear to be rendering/styled correctly. I recreated the theme using the Progress Sass Theme Builder tool to eliminate the stylesheet itself as the issue. I've included screenshots below of what the DropDownList component looks like before and after the upgrade. Can anyone advise? Thanks in advance.

Before upgrade:-

After upgrade:-

Implementation:-

@(Html.Kendo().DropDownListFor(model => model.AssetSubTypeId)
                      .OptionLabel("Asset Type/Subtype...")
                      .BindTo(new SelectList(Lookups.AssetTypeSubType, "Key", "Value"))
                      .Events(events =>
                      {
                          events.Change("onChange_AssetSubTypeDropDownList");
                      }))

Ivan Danchev
Telerik team
 answered on 25 Jan 2022
1 answer
1.4K+ views

I'm following this video tutorial:

https://learn.telerik.com/learn/course/external/view/elearning/3/telerik-ui-for-aspnet-mvc


My application does not appear to be rendering Kendo CSS properly. 

Here is my BundleConfig.cs

    public class BundleConfig
    {
        // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
        public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js"));

            bundles.Add(new ScriptBundle("~/bundles/kendojs").Include(
                        "~/Scripts/kendo/2021.3.1207/kendo.all.min.js",
                        "~/Scripts/kendo/2021.3.1207/kendo.aspnetmvc.min.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/styles/site.css"));

            bundles.Add(new StyleBundle("~/Content/kendocss").Include(
                      "~/Content/kendo/2021.3.1207/kendo.default-v2.min.css"));

            bundles.Add(new StyleBundle("~/Content/dashboardcss").Include(
                "~/Content/styles/dashboard.css"));

            bundles.Add(new StyleBundle("~/Content/backlogcss").Include(
                "~/Content/styles/backlog.css"));

            bundles.Add(new StyleBundle("~/Content/detailcss").Include(
                "~/Content/styles/detail.css"));
        }

 

Here is the head tag in my _Layout.cshtml:


<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>RPS Project Tracker</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/Content/kendocss")
    @Scripts.Render("~/bundles/modernizr")
    @RenderSection("styles", required: false)
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")

    @Scripts.Render("~/bundles/kendojs")

    @Html.Kendo().DeferredScripts()
    @RenderSection("scripts", required: false)
</head>

Here's some examples of the errors in my UI:

in /Backlog/{id}/Details view, my DropDownListFor has no styling attributes:

 

On the Dashboard and Backlog pages, my buttons have broken styling:

Inside DevTools, I'm getting the following error:

 

Any help sorting this out is greatly appreciated.

 

 

Eyup
Telerik team
 answered on 29 Dec 2021
1 answer
218 views

ASP.NET MVC 2020.3.915, development on an enclave network, so upgrading to newer versions takes an act of Congress, and all the code shown here is typed in by hand—meaning if there are any obvious typos, don't take that as the reason it's not working.

I have a DropDownList set up to get a fresh list of items based on Change and Close events on two DatePicker controls, and it works exactly as desired. I am trying to move this same set of controls to an (existing) preferences settings page. I copied the cshtml code verbatim and made appropriate changes, but it's not working.

Here's the control that is working. It sits inside a TabStrip control:


<div class="editor-field">
    @(Html.Kendo().DropDownListFor(m => m.ReportType)
        .Name("ReportType")
        .DataTextField("Text")
        .DataValueField("Value")
        .OptionLabel("Select a Report Type...")
        .DataSource(source =>
        {
            source.Read(read =>
            {
                read.Action("GetFilteredTeams", "Home").Data("get_Dates");
            }).ServerFiltering(true);
        })
        .HtmlAttributes(new { @class = "reportTypeDropdown" }))
</div>

When I inspect this page, I see that this JavaScript was generated:

kendo.SyncReady(function(){jQuery("#ReportType").kendoDropDownList({dataSource":{"transport":{"read":{"url":"/Reporting/Home/GetFilteredTeams","data":getDates},"prefix":""},"serverFiltering":true,"filter":[],"schema":{"errors":"Errors"}},"dataTextField":"Test","dataValueField":"Value","optionLabel":"Select a Report type..."});});


Again, I copied the DropDownList over to the preference page, where it's inside a PanelBar, made appropriate changes, and this is what it looks like: (FWIW, the get_Dates JavaScript function is in a separate JavaScript file associated with the preferences page. Also, the DropDownList is not bound to the model here).

<div class="pref-sub-section-item">
    @(Html.Kendo().DropDownList
        .Name("ReportTypePref")
        .DataTextField("Text")
        .DataValueField("Value")
        .DataSource(source =>
        {
            source.Read(read =>
            {
                read.Action("GetFilteredTeams", "Preferences").Data("get_Dates");
            }).ServerFiltering(true);
        })
        .HtmlAttributes(new { @class = "reportTypeDropdown" }))
</div>

However, this is the JavaScript that gets generated:


kendo.SyncReady(function(){jQuery("#ReportTypePref").kendoDropDownList({"dataTextField":"Test","dataValueField":"Value"});});

If I copy the JS generated from the working page, change the name of the control and the URL, then paste it in the console (or add it to a document.ready block), the DropDownList starts working in sync with the DatePickers.

I've tried fooling with the CSS in case that was erroring out and causing a conflict. I've had my eye on the console, and there are no JS errors popping up. I've also taken the non-working version out of the PanelBar and just pasted the <div> to the root/top level on that page. Same results. No JS, and it doesn't work. I've also tried adding a property to the model and using DropDownListFor (just throwing darts, really), and still, no luck.

It seems the problem is that on my preferences page, Kendo is not generating the full JS for some reason. This is such a massive project that it's not really feasible to create a discrete model where the problem is repeatable. I realize without viewing the full project, it will be hard to pinpoint, but I'm just looking for some help on how to troubleshoot what's going on here, since looking under the hood of Kendo has it's limits.

Oh, also, the page that is working is \Reporting\Home\Index.cshtml — the page that is not working is \Preferences\Index.cshtml
John
Top achievements
Rank 1
Iron
 answered on 10 Dec 2021
1 answer
86 views

Hi Team,

I am using Kendo UI MVC Grid and trying to override the checkbox style using FontAwesome fonts. I thought of doing it through CSS alone but since we can't select parent selector through CSS I ended up using the filterMenuInit event. 

Grid column is configured using:-

.Filterable(f => f.Multi(true).Search(true));

I am adding another label to the rendered checkbox text using the below function:-


 function addCustomLabel(e) {
            var container = e.container;
            var allCheckboxes = $("input[type='checkbox']", container);
            $.each(allCheckboxes, function (id) {
                $(this).attr("id", 'chk' + id).addClass("blueCheckbox");
                var checkbox = $(this)[0];
                console.log(checkbox);
                var parentLabel = $(this).parent('label');
                var labelText = parentLabel.text();
                parentLabel.empty();
                parentLabel.append(checkbox);
                parentLabel.append("<label for='"+ 'chk' + id +"'>" + labelText + "</label>");
            });
        }
It's working as expected i.e. adding an id to checkbox and label with "for" attribute but only the "Select All" checkbox is not working. I am assuming it's because kendo is checking for text "Select All" which is now wrapped inside a label. Could you please suggest a fix for this? Or please let me know if there is any better way to do this. 
Eyup
Telerik team
 answered on 08 Dec 2021
1 answer
126 views

The ComboBox control appears to have a configuration called HighlightFirst which supresses the automatic highlighting of the first list item as the user types.

Is there any way of implementing this same logic on the DropDownList control? By default, it appears to highlight / focus on the first option in the list when the user begins to type.

@(Html.Kendo().DropDownList()
        .Name("Sku")
        .DataValueField("Value")
        .DataTextField("Text")
        .//HighlightFirst(false)
        .Filter("contains")
        .AutoBind(false)
        .BindTo(new List<SelectListItem>()
                {
                    new SelectListItem(){ Value = "ZIP100", Text = "ZIP100 - Zip Active Stool | Stock | 400H-550H | Purple Moon	" },
                    new SelectListItem(){ Value = "ZIP101", Text = "ZIP101 - Zip Active Stool | Stock | 400H-550H | Juice Green" },
                    new SelectListItem(){ Value = "ZIP102", Text = "ZIP102 - Zip Active Stool | Stock | 400H-550H | Capri Mid Blue" },
                    new SelectListItem(){ Value = "ZIP103", Text = "ZIP103 - Zip Active Stool | Clearance | 400H-550H | Opal Light Blue" },
                    new SelectListItem(){ Value = "ZIP104", Text = "ZIP104 - Zip Active Stool | Clearance | 400H-550H | Oyster Grey" },
                    new SelectListItem(){ Value = "ZIP105", Text = "ZIP105 - Zip Active Stool | Clearance | 400H-550H | Melon Rush" },
                    new SelectListItem(){ Value = "ZIP106", Text = "ZIP106 - Zip Active Stool | Stock | 400H-550H | Charcoal" },
                    new SelectListItem(){ Value = "ZIP107", Text = "ZIP107 - Zip Active Stool | Clearance | 400H-550H | Capri Blue with NC Whale Seat Pad" },
                    new SelectListItem(){ Value = "ZIP108", Text = "ZIP108 - Zip Active Stool | Clearance | 400H-550H | Juice Green with NC Whale Seat Pad" },
                    new SelectListItem(){ Value = "ZIP109", Text = "ZIP109 - Zip Active Stool | Clearance | 400H-550H | Melon Rush with NC Whale Seat Pad" },
                    new SelectListItem(){ Value = "ZIP110", Text = "ZIP110 - Zip Active Stool | Clearance | 400H-550H | Opal Blue with NC Whale Seat Pad" },
                    new SelectListItem(){ Value = "ZIP111", Text = "ZIP111 - Zip Active Stool | Clearance | 400H-550H | Oyster Grey with NC Whale Seat Pad" },
                    new SelectListItem(){ Value = "ZIP112", Text = "ZIP112 - Zip Active Stool | Clearance | 400H-550H | Purple Moon with NC Whale Seat Pad" }
                })
    )

 

 

 

Yanislav
Telerik team
 answered on 04 Nov 2021
0 answers
265 views

Are there any online examples of where a dropdrownlist control is used inline as a column with the MVC TreeList?

I need the column to be active at all times,.  We don't want to utilize the popup editor.

I tried adding a column with a template like this:

            @(Html.Kendo().TreeList<VendorPortalCatalogItem>()
                  .Name("myClassTreelist")
                  .Columns(columns =>
                  {
                      columns.Add().Field(e => e.Name).Width(220).TemplateId("name-template");
                      columns.Add().Field(e => e.DaysToShipId).TemplateId("dts-template");
                  })
                  .Filterable()
                  .Sortable()
                  .DataSource(dataSource => dataSource
                      .Read(read => read.Action("TreeList_LoadAll", "DaysToShip"))
                      .ServerOperation(false)
                      .Model(m =>
                      {
                          m.Id(f => f.Id);
                          m.ParentId(f => f.ParentId);
                          m.Field(f => f.Name);
                          m.Field(f => f.IconClass);
                      })
                  )
                  .Height(540)
                  )


And my template looks like this:

<script id="dts-template" type="text/x-kendo-template">

            @(Html.Kendo().DropDownList()
                  .Name("DaysToShipId")
                  .OptionLabel("Select days to ship...")
                  .HtmlAttributes(new { style = "width: 100%" })
                  .DataTextField("Text")
                  .DataValueField("Value")
                  .DataSource(source =>
                  {
                      source.Read(read =>
                      {
                          read.Action("ddlDaysToShip_Read", "DaysToShip");
                      });
                  })
                  .Height(400)
                  )

</script>


 

But all this does is throw console error "Uncaught error: Invalid template"

Joe
Top achievements
Rank 1
 asked on 01 Oct 2021
Narrow your results
Selected tags
Tags
+? more
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Mark
Top achievements
Rank 1
Yurii
Top achievements
Rank 1
Leland
Top achievements
Rank 2
Iron
Iron
Iron
Hon
Top achievements
Rank 1
Iron
Deltaohm
Top achievements
Rank 3
Bronze
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?