Telerik Forums
UI for ASP.NET Core Forum
6 answers
1.3K+ views

hi ..

i have a dto class called GroupListDto with just three fields

public class GroupListDto
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

 

i use this class as kendo grid model ..

when i write my actionresult in below manner . my model field is empty

public ActionResult Create([DataSourceRequest] DataSourceRequest request, GroupListDto group)

 

but when is use GroupListDto class fields instead , the fields are filled with correct datas

public ActionResult Create([DataSourceRequest] DataSourceRequest request, string Title , string Description)

 

does anyone know what is the problem ?

why i cant get data in my dto model , but i get data in its fields !?


Petar
Telerik team
 answered on 06 Aug 2020
1 answer
226 views

I am using .net core 3.5 and razor pages.   I have a file upload control that is calling OnPost even when the control explicitly says to call a different method name.

  @(Html.Kendo().Upload()
            .Name("files")
            .Multiple(false)
            .Async(a => a
                .Save("Async_Save", "New", new { Question = DebtorDropBox.Web.UI.Code.Question.DriversLicense })
                .AutoUpload(true)
            )
            .Events(e => e
                .Success("onSuccess")
                .Upload("onUpload")
                .Error("onError")
            )
            .Validation(validation => validation.AllowedExtensions(new string[] { ".jpg" }))
            .Validation(validation => validation.MaxFileSize(4000000))
        )

      for testing purposes I have added the following three methods to my page and no matter what It keeps calling OnPost.    Is there something I should be doing? 

        public async Task<ActionResult> Async_Save(IEnumerable<IFormFile> files, Question question)
        {
            return Page();
        }

        public async Task<ActionResult> OnPostAsync_Save(IEnumerable<IFormFile> files, Question question)
        {
            return Page();
        }

        public async Task<ActionResult> OnPost(IEnumerable<IFormFile> files, Question question)
        {
            return Page();
        }

Martin
Telerik team
 answered on 05 Aug 2020
9 answers
1.5K+ views

How do I handle an exception that occurs when generating the data to be sent to the grid?  I've seen an example of a call to a Javascript "error_handler" method.  Is that my only option?

<kendo-grid name="grid">
    <datasource type="DataSourceTagHelperType.Ajax" on-error="Error">
        <transport>
            <read url="Home/GetOrgs" />
        </transport>
    </datasource>
    ...
</kendo-grid>

 

public IActionResult GetOrgs([DataSourceRequest] DataSourceRequest request)
{
    int x = 0; int r = 10 / x;
}

 

 

Anton Mironov
Telerik team
 answered on 04 Aug 2020
1 answer
168 views

I have a grid very similar to the one in this telerik example where I am using 3 different client templates to populate and bind 3 drop downs in my grid:

https://demos.telerik.com/aspnet-core/grid/editing-custom

My dropdowns are: Category, Department, Configuration

 

So my grid is defined like this with custom editors

columns.Bound(e => e.Category).ClientTemplate("#=Category.CategoryName#").Title("Category");
columns.Bound(e => e.Department).ClientTemplate("#=Department.DepartmentName#").Title("Department");
columns.Bound(e => e.Configuration).ClientTemplate("#=Configuration.ConfigurationName#").Title("Configuration");

And the model I'm binding to looks just like in the example:

[System.ComponentModel.DataAnnotations.UIHint("Category")]
public CategoryViewModel Category {
    get;
    set;
}
 
[System.ComponentModel.DataAnnotations.UIHint("Department")]
public DepartmentViewModel Department {
    get;
    set;
}
 
[System.ComponentModel.DataAnnotations.UIHint("Configuration")]
public ConfigurationViewModel Configuration{
    get;
    set;
}

 

I need the dropdowns to cascade.....choose a Category, it loads Departments associated with that category, choose a Department, it loads configurations associated with that department. So my code in the custom editor is simply (this is for category, for department it passes the selected categoryId in the read action , etc)

@model DMA.Model.CategoryViewModel
<script>
    function onCategoryChange(e) {
       $("#Department").data("kendoDropDownList").dataSource.read();   
    }
</script>
@(Html.Kendo().DropDownListFor(m => m)
.DataValueField("CategoryID")
        .DataTextField("CategoryName")
        .DataSource(source => {
         source.Read(read =>
            {
                read.Action("GetCategories", "Wizard");
            });
        }).Events(e => e.Change("onCategoryChange"))
)

 

And visually works correctly, choosing a category will re-fill the department options and by default the first item is now selected. But if you go to save it at this point, even though the first item is selected, the model does not reflect that: e.model.Department = null. You have to physically choose an item from the Department drop down to get it to set that model value correctly. What is going on here? Why is not binding the model to the selected item when it refills? 

 

 

Anton Mironov
Telerik team
 answered on 03 Aug 2020
3 answers
755 views

Afternoon

 

Using Package Telerik.UI.for.AspNet.Core(2020.2.617)

 

Goal: 

I want to switch Kendo Menu to use k-i-menu rather than font awsome icon.

 

Problem

It is always blank when i reference the k-i-menu. This is because it adds k-sprite into the span it generates and that seems to cause the issues

e.g. <span class="k-sprite k-icon k-i-menu k-icon-32"></span>

Example Code

<span class="k-icon k-i-menu k-icon-32"></span> <-- this shows bars
<div style="padding-right: 5px" class="k-content">
    @(Html.Kendo().Menu().Name("NavMenu").Items(items =>
    {items.Add()
            .Items(innerChilderen =>
            {
                innerChilderen.Add().Text("Reports").Url("/Something");
            }).SpriteCssClasses("k-icon k-i-menu k-icon-32");  <--- this is blank
    }))
</div>

 

I assumed it would be an easy switch since it was already working with font awesome. Not sure if i'm missing something as far as using the kendo icons with this menu. Looking forward to your thoughts.

 

 

 

 

 

Dimitar
Telerik team
 answered on 03 Aug 2020
3 answers
471 views

After upgrading from 2.2 to 3.1 my grid control no longer works.  I am available for a phone call if that is easier.

Note: I have success with Html.Kendo().Menu() but also failure on Html.Kendo().TreeList<Group>().  I verified I have valid data.

Project:

<Project Sdk="Microsoft.NET.Sdk.Web" ToolsVersion="15.0">
 
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    <AssemblyName>Gsi.Portal</AssemblyName>
  </PropertyGroup>
 
  <ItemGroup>
    <Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
  </ItemGroup>
 
  <ItemGroup>
    <PackageReference Include="bootstrap" Version="4.5.0" />
    <PackageReference Include="IdentityModel" Version="4.3.1" />
    <PackageReference Include="IdentityServer4" Version="4.0.3" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.14.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Abstractions" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="3.1.6" />
    <PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="2.2.0" />
    <PackageReference Include="Microsoft.Azure.KeyVault.Core" Version="3.0.5" />
    <PackageReference Include="Microsoft.Azure.Storage.Blob" Version="11.1.7" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.3" />
    <PackageReference Include="System.Text.Encodings.Web" Version="4.7.1" />
    <PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
    <PackageReference Include="Telerik.UI.for.AspNet.Core" Version="2020.2.617" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="Telerik.Web.PDF" Version="2020.2.617" />
    <PackageReference Include="NLog.Web.AspNetCore" Version="4.9.2" />
  </ItemGroup>

Shared._Layout:

I note that on this training your header looks different than mine.  Do I need to completely rework this?

https://docs.telerik.com/aspnet-core/getting-started/first-steps#adding-reference-to-kendomvcui

<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@Glossary.Company Portal - @ViewData["Title"]</title>
 
    <link href="https://kendo.cdn.telerik.com/2020.2.617/styles/kendo.bootstrap-v4.min.css" rel="stylesheet" type="text/css" />
 
 
    <environment names="Development">
        <link rel="stylesheet" type="text/css" href="~/lib/bootstrap/css/bootstrap.css" />
        <link rel="stylesheet" type="text/css" href="~/css/site.css" />
    </environment>
    <environment names="Staging,Production">
              asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
    <link rel="stylesheet" type="text/css" href="~/css/GsiWebPortalBootstrapTheme.css" />
</head>

_ViewImports.cshtml

@using Gsi.Portal
@using Kendo.Mvc.UI
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Kendo.Mvc

 

 

Grid:

@(Html.Kendo().Grid<Person>()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Command(command => command
            .Custom("Detail")
            .Click("goDetail"))
            .Width(Glossary.Portal.ButtonWidth);
        columns.Bound(p => p.FirstName);
        columns.Bound(p => p.LastName);
    })
    .Pageable()
    .Sortable()
    .Scrollable()
    .HtmlAttributes(new { style = "height:550px;" })
    .DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Read(read => read.Action("IndexJson", "Users")
            .Data("getGridData"))
        .Model(m => m.Id(p => p.Id))
    ))

Callback:

if (response.IsSuccess)
{
    var persons = response.Result;
    if (persons != null)
    {
        var dsResult = await persons.ToDataSourceResultAsync(request);
        return Json(dsResult);
    }
    else
    {
        return CustomResponseToError(response);
    }
}

 

Nikolay
Telerik team
 answered on 30 Jul 2020
5 answers
288 views

I'm migrating some code from netFramework asp.net to asp.net core and I found some unexpected behavior with an editor used everywhere in my old code.

I'm bounding a timestamp property in a table like this:

columns.Bound(m => m.TimeSpan);

 

And I have an editor template for timestamps:

@model TimeSpan
 
@Html.Kendo().IntegerTextBoxFor(model=>model.Hours).Spinners(false).HtmlAttributes(new {style = "width: 30px" }).Placeholder("HH").Format("00") :
@Html.Kendo().IntegerTextBoxFor(model => model.Minutes).Min(0).Max(59).HtmlAttributes(new {style = "width: 30px;" }).Placeholder("MM").Spinners(false).Format("00")

 

If I load the page containing the table y get an exception:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ExpressionMetadataProvider.<>c__DisplayClass0_0`2.<FromLambdaExpression>g__modelAccessor|0(Object container)
   at Microsoft.AspNetCore.Mvc.ViewFeatures.ModelExplorer.get_Model()
   at Kendo.Mvc.UI.Fluent.WidgetFactory`1.NumericTextBoxFor[TValue](Expression`1 expression)
   at Kendo.Mvc.UI.Fluent.WidgetFactory`1.IntegerTextBoxFor(Expression`1 expression)
.....

 

The EditorTemplate works normally if I use in other pages like:

@Html.EditorFor(m=>m.TimeSpan)

 

 

Thanks

Petar
Telerik team
 answered on 29 Jul 2020
1 answer
40 views

    I creatred a new project using the Telerik template.  By default, the IAntiforgery token was injected.  In order to use that token, the Datasource invokes it this way:

    .DataSource(ds => ds.Ajax()
            .Read(r => r.Url("/Index?handler=Read").Data("forgeryToken"))

 

That .Data references to a script like this:

<script>
    function forgeryToken() {
        return kendo.antiForgeryTokens();
    }
</script>

Question... if I have additional data to include, how is the forgeryToken included?

I use a script like this:

function gridGetData() {
    //alert("grid.gridGetData");
    //alert("customerId: " + customerId);
 
    var groupId = $("#groupId").val();
 
    if (groupId != null && groupId !== 0) {
 
        var firstName = $("#firstNameFilter").val();
        var lastName = $("#lastNameFilter").val();
        var isActive = $("#isActiveOptions").val();
         
        //alert("gridGetData - firstName: " + firstName);
        //alert("gridGetData - lastName: " + lastName);
        //alert("gridGetData - isActive: " + isActive);
 
        return {
            customerId: customerId,
            customerUniqueId: customerUniqueId,
            groupId: groupId,
            sessionId: sessionId,
            firstNameFilter: firstName,
            lastNameFilter: lastName,
            isActiveFilter: isActive
        };
    } else {
        return @Html.Raw(Model.GetIndexData());
    }
}

 

Tsvetomir
Telerik team
 answered on 29 Jul 2020
1 answer
604 views

Is it possible to do use a dynamic editor on a column with C# wrappers, like the example below does for jquery?  

https://docs.telerik.com/kendo-ui/knowledge-base/grid-use-dynamic-editor

How can I achieve similar functionality?  

I have a simple Preference object that can have different types of values.  (Boolean, String, Number, etc).  

The preference object has a DataType that tells it what type for each row.  I would like to use this value to determine what editortemplate to use.  

Thank you very much for your help.  

 

Neli
Telerik team
 answered on 28 Jul 2020
4 answers
144 views

I based the implementation on the example video about TagHelpers. But no data is displayed. A call to the URL (https://localhost:44337/Suppliers/Read) provides data. What am I doing wrong?

SuppliersController:

001.using System;
002.using System.Collections.Generic;
003.using System.Linq;
004.using System.Threading.Tasks;
005.using Kendo.Mvc.Extensions;
006.using Kendo.Mvc.UI;
007.using Microsoft.AspNetCore.Mvc;
008.using Microsoft.AspNetCore.Mvc.Rendering;
009.using Microsoft.EntityFrameworkCore;
010.using VIMANTO.EasyOrder.Data;
011.using VIMANTO.EasyOrder.Models;
012. 
013.namespace VIMANTO.EasyOrder.Controllers
014.{
015.    public class SuppliersController : Controller
016.    {
017.        private readonly ApplicationDbContext _context;
018. 
019.        public SuppliersController(ApplicationDbContext context)
020.        {
021.            _context = context;
022.        }
023. 
024.        [HttpGet]
025.        public ActionResult Read()
026.        {
027.            return Json(_context.Suppliers.Where(s => s.IsDeleted == false).ToList());
028.        }
029. 
030.        // GET: Suppliers
031.        public async Task<IActionResult> Index()
032.        {
033.            return View(await _context.Suppliers.Where(s => s.IsDeleted == false).ToListAsync());
034.        }
035. 
036.        // GET: Suppliers/Details/5
037.        public async Task<IActionResult> Details(int? id)
038.        {
039.            if (id == null)
040.            {
041.                return NotFound();
042.            }
043. 
044.            var supplier = await _context.Suppliers
045.                .FirstOrDefaultAsync(m => m.Id == id);
046.            if (supplier == null)
047.            {
048.                return NotFound();
049.            }
050. 
051.            return View(supplier);
052.        }
053. 
054.        // GET: Suppliers/Create
055.        public IActionResult Create()
056.        {         
057.            return View();
058.        }
059. 
060.        // POST: Suppliers/Create
061.        // To protect from overposting attacks, enable the specific properties you want to bind to, for
062.        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
063.        [HttpPost]
064.        [ValidateAntiForgeryToken]
065.        public async Task<IActionResult> Create([Bind("Id,InternalNumber,Name,AdditionalName,Street,Postcode,City,Phone,Fax,Mail,Web,CustomerNumber")] Supplier supplier)
066.        {
067.            if (ModelState.IsValid)
068.            {
069.                _context.Add(supplier);
070.                await _context.SaveChangesAsync();
071.                return RedirectToAction(nameof(Index));
072.            }
073.            return View(supplier);
074.        }
075. 
076.        // GET: Suppliers/Edit/5
077.        public async Task<IActionResult> Edit(int? id)
078.        {
079.            if (id == null)
080.            {
081.                return NotFound();
082.            }
083. 
084.            var supplier = await _context.Suppliers.FindAsync(id);
085.            if (supplier == null)
086.            {
087.                return NotFound();
088.            }
089.            return View(supplier);
090.        }
091. 
092.        // POST: Suppliers/Edit/5
093.        // To protect from overposting attacks, enable the specific properties you want to bind to, for
094.        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
095.        [HttpPost]
096.        [ValidateAntiForgeryToken]
097.        public async Task<IActionResult> Edit(int id, [Bind("Id,InternalNumber,Name,AdditionalName,Street,Postcode,City,Phone,Fax,Mail,Web,CustomerNumber")] Supplier supplier)
098.        {
099.            if (id != supplier.Id)
100.            {
101.                return NotFound();
102.            }
103. 
104.            if (ModelState.IsValid)
105.            {
106.                try
107.                {
108.                    _context.Update(supplier);
109.                    await _context.SaveChangesAsync();
110.                }
111.                catch (DbUpdateConcurrencyException)
112.                {
113.                    if (!SupplierExists(supplier.Id))
114.                    {
115.                        return NotFound();
116.                    }
117.                    else
118.                    {
119.                        throw;
120.                    }
121.                }
122.                return RedirectToAction(nameof(Index));
123.            }
124.            return View(supplier);
125.        }
126. 
127.        // GET: Suppliers/Delete/5
128.        public async Task<IActionResult> Delete(int? id)
129.        {
130.            if (id == null)
131.            {
132.                return NotFound();
133.            }
134. 
135.            var supplier = await _context.Suppliers
136.                .FirstOrDefaultAsync(m => m.Id == id);
137.            if (supplier == null)
138.            {
139.                return NotFound();
140.            }
141. 
142.            return View(supplier);
143.        }
144. 
145.        // POST: Suppliers/Delete/5
146.        [HttpPost, ActionName("Delete")]
147.        [ValidateAntiForgeryToken]
148.        public async Task<IActionResult> DeleteConfirmed(int id)
149.        {
150.            var supplier = await _context.Suppliers.FindAsync(id);
151.            supplier.IsDeleted = true;
152.            await _context.SaveChangesAsync();
153.            return RedirectToAction(nameof(Index));
154.        }
155. 
156.        private bool SupplierExists(int id)
157.        {
158.            return _context.Suppliers.Any(e => e.Id == id);
159.        }
160.    }
161.}

 

Index.chtml:

01.@{
02.    ViewData["Title"] = "Lieferanten";
03.    Layout = "~/Views/Shared/_Layout.cshtml";
04.}
05. 
06.<div class="row">
07.    <div class="col-xs-12">
08.        <h3 class="k-text-info">Lieferanten verwalten</h3>
09.        <partial name="_SuppliersGrid" />
10.    </div>
11.</div>

 

_SuppliersGrid:

01.<kendo-grid name="SuppliersGrid" height="550" auto-bind="false">
02.    <columns>
03.        <column field="Name" title="Lieferant" />
04.        <column field="AdditionalName" title="Zusatz" min-screen-width="768" />
05.            <column field="Street" title="Strasse" />
06.            <column field="Postcode" min-screen-width="768">
07.                <filterable multi="true"></filterable>
08.            </column>
09.            <column field="City" title="Ort" />
10.    </columns>
11. 
12.    <datasource type="DataSourceTagHelperType.Ajax" page-size="20">
13.        <schema>
14.                <model>
15.                    <fields>
16.                        <field name="Id" type="number"></field>
17.                    </fields>
18.                </model>
19.            </schema>
20.        <transport>
21.            <read url="@Url.Action("Read", "Suppliers")" />
22.        </transport>
23.        <sorts>
24.                <sort field="Name" direction="asc" />
25.            </sorts>
26.    </datasource>
27.    <groupable enabled="true" />
28.        <sortable enabled="true" />
29.    <pageable button-count="5" refresh="true" />
30.    <filterable enabled="true" />
31.</kendo-grid>
Harald
Top achievements
Rank 2
 answered on 27 Jul 2020
Narrow your results
Selected tags
Tags
+? more
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Anislav
Top achievements
Rank 6
Silver
Bronze
Bronze
Jianxian
Top achievements
Rank 1
Iron
Marco
Top achievements
Rank 3
Iron
Iron
Iron
Jim
Top achievements
Rank 2
Iron
Iron
Nurik
Top achievements
Rank 2
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?