Telerik Forums
UI for ASP.NET Core Forum
7 answers
111 views

Hello,

I have a grid with derived objects and I would like to open different edit popup for each type of child object.

I'll give a simplified example:

Models:

public class Product
{
        public string Label { get; set; }
}
public class TypeA: Product
{
        public string PropA { get; set; }
}
public class TypeB: Product
{
        public int PropB { get; set; }
}
 
public class Order
{
        public int Id {get;set;}
        public virtual ICollection<Product> Products { get; set; }
}

 

Controller:

public async Task<Order> GetById(int id)
{
    Order order = await webApi.GetById(id); // webApi is a private service who calls a json converter to return a strongly typed list with derived class
    return order ;
}

 

At this point, the object order have a Products property which is a collection of TypeA, TypeB and Product

Views:

@model Order
<div>
    @(Html.Kendo().Grid<Product>(Model.Products).Name("grid")
        .Editable(editable => editable.Mode(GridEditMode.PopUp))
        .Columns(columns =>
        {
            columns.Bound(p => p.Label);
            columns.Command(command => { command.Edit(); });
        })
    )
</div>

 

I also create templates in Views\Shared\EditorTemplates

@model Product
 
<div>
    <h1>Product</h1>
</div>
 
-------------------------
 
@model TypeA
 
<div>
    <h1>TypeA</h1>
</div>
 
-------------------------
 
@model TypeB
 
<div>
    <h1>TypeB</h1>
</div>

 

Only the Product template pops up. I guess it's because of Grid<Product> declaration.

How can I strongly typed each row and/or have different editor template? I don't want to show PropA and PropB in my grid but I want to allow to edit them in the popup.

Thanks

 

Georgi
Telerik team
 answered on 31 May 2019
5 answers
146 views

Sir,

I have an asp.net core 2.2 project, and I wanted to use Telerik grid to display data from the MS SQL Server database.

the model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
 
namespace SUCOCoreControl.Models.RazorBudget
{
    public partial class Header
    {
        public Header()
        {
            SubHeader = new HashSet<SubHeader>();
        }
 
        [StringLength(6)]
        public string ProjectID { get; set; }
        [StringLength(30)]
        public string HeaderID { get; set; }
        [StringLength(60)]
        public string HeaderENG { get; set; }
        [StringLength(60)]
        public string HeaderARB { get; set; }
 
        [ForeignKey("ProjectID")]
        [InverseProperty("Header")]
        public virtual Project Project { get; set; }
        [InverseProperty("Header")]
        public virtual ICollection<SubHeader> SubHeader { get; set; }
    }
}

The controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SUCOCoreControl.Models.RazorBudget;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using SUCOCoreControl.Data;
 
namespace SUCOCoreControl.Controllers
{
    public class HeadersController : Controller
    {
        private readonly SUCODbContext _context;
 
        public HeadersController(SUCODbContext context)
        {
            _context = context;
        }
 
        public IActionResult Index([DataSourceRequest] DataSourceRequest request)
        {
            return Json(_context.Header.ToDataSourceResult(request));
        }
        public IActionResult Error()
        {
            return View();
        }
 
    }
}

 

The view

@using SUCOCoreControl.Models.RazorBudget
 
@{
    ViewData["Title"] = "Headers";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<!-- ============================================================== -->
<!-- Page wrapper  -->
<!-- ============================================================== -->
<div class="page-wrapper">
    <!-- ============================================================== -->
    <!-- Container fluid  -->
    <!-- ============================================================== -->
    <div class="container-fluid">
        <!-- ============================================================== -->
        <!-- Bread crumb and right sidebar toggle -->
        <!-- ============================================================== -->
        <div class="row page-titles">
            <div class="col-md-5 align-self-center">
                <h4 class="text-themecolor"><a> @ViewBag.Title</a></h4>
            </div>
        </div>
        <!-- ============================================================== -->
        <!-- End Bread crumb and right sidebar toggle -->
        <!-- ============================================================== -->
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="col-md-6 col-xs-12">
                            <div class="form-inline well well-lg">
                                @(Html.Kendo().Grid<Header>()
           .Name("Header")
           .Columns(columns =>
           {
               columns.Bound(p => p.ProjectID);
               columns.Bound(p => p.HeaderID);
               columns.Bound(p => p.HeaderENG);
               columns.Bound(p => p.HeaderARB);
               columns.Command(command => command.Edit());
           })
           .Pageable()
           .Sortable()
           .Filterable()
           .Groupable()
           .Editable()
 
                     .DataSource(dataSource => dataSource
               .Ajax()
             .ServerOperation(false)
             .Read(read => read.Action("Index", "Headers"))
            )
                                )
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

 

The page is not loading, and the grid of course is not.

I attached the result in the browser.

What I am doing wrong???

Tsvetomir
Telerik team
 answered on 30 May 2019
4 answers
140 views

Hi,

I want to put the checked sign <i class='fa fa-check' aria-hidden='true'></i> to replace "true" in the grid column.

 

I put below code:

@{     var freshnessTemplate = "# if (checkFreshness) { # <i class='fa fa-check' aria-hidden='true'></i> # } #";}

then

columns.Bound(p => p.checkFreshness).Title("Check Fresh").Width(150).ClientTemplate(freshnessTemplate).HtmlAttributes(new { style = "text-align: center" });

 

but it doesn't show the checked sign.

Viktor Tachev
Telerik team
 answered on 29 May 2019
2 answers
164 views

Hello,

I am updating my project from 2019.1.220 to 2019.2.514. (Telerik UI for ASP.NET Core)

 

After updating the nuget-package, the namespace Kendo could not be found.

I have the same issue with the example project, comming with the msi installer.

 

What am I missing?

Thanks

Michael

 

Michael
Top achievements
Rank 1
Iron
 answered on 29 May 2019
1 answer
432 views

I have a div that has 7 different elements that I want to make readonly.  Right now I have the following script that is setting all non kendo items to readonly

$("#GroupBox").find('input, label').attr("readonly", true)

 

I have 4 dropdownlists, 2 sliders, and 1 datepicker that I also want to make readonly.  I know that I can set each of them individually, but is there an easier way? something similar to what I can do for non kendo component?

Konstantin Dikov
Telerik team
 answered on 28 May 2019
4 answers
1.4K+ views

Hi,

I have got a form that contains 1 multiselect, 2 dropdown list, 1 button for filtering  and 1 grid  controls.  Every control is required for filter parameters.

For example;

When user click Filter button I will get Multiselect control's selected values, dropdown list control's values and send them to my Action Result method that filling my grid control and in this method my linq query will build and refresh the Grid's datasource.

But i dont know how to get selected values to and then send it to Action Method for re-build my linq query and refresh grid.  

Here is my Grid at Razor Page.

@(Html.Kendo().Grid<TelerikAspNetCoreDroppedCalls.Models.CallcentQueuecalls>()
                                                      .Name("grid")
                                                      .Columns(columns =>
                                                      {
                                                          columns.Bound(p => p.FromUserpart);
                                                          columns.Bound(p => p.TimeStart).Format("{0:dd/MM/yyyy hh:ss}");
                                                          columns.Bound(p => p.TimeEnd).Format("{0:dd/MM/yyyy hh:ss}");
 
 
                                                      })
                                                      .Pageable()
                                                      .Sortable()
                                                      .Scrollable()
 
                                                      .HtmlAttributes(new { style = "height:550px;" })
                                                      .DataSource(dataSource => dataSource
                                                          .Ajax()
                                                          .ServerOperation(false)
                                                          .PageSize(20)
                                                          .Read(read => read.Action("CallQueues_Read", "Grid")
          )
                                                      )
      )

Here is my Action Method for filling Grid.

public async Task<ActionResult> CallQueues_Read([DataSourceRequest]DataSourceRequest request)
 
        {
             
            var query = from r in _db.CallcentQueuecalls
                where !(r.ReasonNoanswercode == 0 && r.ReasonFailcode == 0 &&
                        r.ToDn != null && r.TsServicing != null)
                        && (r.TimeStart >= DateTime.Today.AddDays(-3)) && r.QNum=="0010"
                 
                        select r;
 
           
            var dsResult = await query.ToDataSourceResultAsync(request);
            return Json(dsResult);
        }
Tsvetina
Telerik team
 answered on 27 May 2019
1 answer
160 views

So I've been trying out kendo core components and cannot get it to work with the sample codes from core.
Some components such as Autocomplete and Datepicker does work but when trying out for example a pie chart the component does not show for some reason. 

Any suggestions on what the problem could be?

I've added pngs for the code below.

This works:

<div class="cards" style="height: 60%; flex-direction: row">
                <div class="card mb-3 shadow card-theme" style="width: 35%; max-height: 100%; margin-right:20px;">
                    <div class="card-body" style="flex-direction:row">
                        <div id="phoenixPieChart" style="width:100%; height:50%;">
                             
                                @(Html.Kendo().DatePicker()
                                    .Name("DatePicker")
                                )
                        </div>
                </div>
        </div>
</div>

This doens't work:

<div class="cards" style="height: 60%; flex-direction: row">
                <div class="card mb-3 shadow card-theme" style="width: 35%; max-height: 100%; margin-right:20px;">
                    <div class="card-body" style="flex-direction:row">
                        <div id="phoenixPieChart" style="width:100%; height:50%;">
                                @(Html.Kendo().Chart()
                                            .Name("chart")
                                                    .Title(title => title
                                                        .Text("Share of Internet Population Growth, 2007 - 2012")
                                                        .Position(ChartTitlePosition.Bottom))
                                            .Legend(legend => legend
                                                .Visible(false)
                                            )
                                            .ChartArea(chart => chart
                                                .Background("transparent")
                                             )
                                            .HtmlAttributes(new { style = "background: center no-repeat url(" + @Url.Content("~/shared/world-map.png") })
                                            .Series(series =>
                                            {
                                                series.Pie(new dynamic[] {
                                        new {category="Asia",value=53.8,color="#9de219"},
                                        new {category="Europe",value=16.1,color="#90cc38"},
                                        new {category="LatinAmerica",value=11.3,color="#068c35"},
                                        new {category="Africa",value=9.6,color="#006634"},
                                        new {category="MiddleEast",value=5.2,color="#004d38"},
                                        new {category="NorthAmerica",value=3.6,color="#033939"}
                                                })
                                                .Labels(labels => labels
                                                    .Template("#= category #: \n #= value#%")
                                                    .Background("transparent")
                                                    .Visible(true)
                                                )
                                                .StartAngle(150);
                                            })
                                            .Tooltip(tooltip => tooltip
                                                .Visible(true)
                                                .Format("{0}%")
                                            )
                                )
                             
                        </div>
                </div>
         </div>
  </div>

Tsvetomir
Telerik team
 answered on 24 May 2019
1 answer
1.9K+ views

"[Bind(Prefix = "models")] " in    https://demos.telerik.com/aspnet-core/grid/editing

I strictly followed the code in this page, but my save updates doesn't work.  

Georgi
Telerik team
 answered on 24 May 2019
1 answer
90 views

Hello,

I'm new to UI for Asp.net core. I met a problem here.

 

I have a table "authors" , contains all the author id [A,B,D,G,F]

and I have another table "books", it will be a Grid, showing book name, author name, when inline editing, user can update the author name for the book. when user input 'C', then notify him put a wrong author name. because our list is [A,B,D,G,F] has no C.

 

how to do this?   or how to put a check box list when inline editing a row in Grid?

Georgi
Telerik team
 answered on 23 May 2019
4 answers
431 views

I'm getting a 400 Error when I click on the toolbar button to export the grid contents to Excel.  The call to the ProxyURL method never happens.

Chrome Dev Tools shows the following.

POST https://localhost:44329/Admin/Companies?handler=Read 400

I suspect this is because the Anti-Forgery token is not getting passed to the read that the export function uses although it looks like the same read call that the grid uses successfully.  Any ideas on how I can resolve this?

@(Html.Kendo().Grid<InstallerCompanyPageModel>()
    .AutoBind(false)
    .Name("CompaniesGrid")
    .Columns(columns =>
    {
        columns.Command(command => { command.Edit()
            .HtmlAttributes(new { title = "Edit", @class = "k-button k-button-icontext" })
            .UpdateText("Save"); }).Width(100);
        columns.Bound(a => a.CompanyName).Width(200)
            .Filterable(filterable => filterable.Extra(false)
                .Operators(operators => operators
                    .ForString(str => str.Clear()
                        .StartsWith("Starts with")
                        .Contains("Contains")
                    ))
            );
        columns.Bound(a => a.WebSite).Width(250)
            .HtmlAttributes(new { @class = "wordWrapGridColumn" })
            .Filterable(filterable => filterable.Extra(false)
            .Operators(operators => operators
                .ForString(str => str.Clear()
                    .StartsWith("Starts with")
                    .Contains("Contains")
                ))
            );
        columns.Bound(a => a.Active).Width(60)
            .ClientTemplate("#= Active ? 'Yes' : 'No' #").HtmlAttributes(new { style = "text-align:center" });
    })
    .ToolBar(toolbar => toolbar.Custom().Text("<i class='fas fa-file'></i> Add New")
        .HtmlAttributes(new { id = "companyAdd", title = "Add a new company.", @class = "k-button k-button-icontext k-grid-add" }))
    .ToolBar(toolbar => toolbar.Custom().Text("<i class='fas fa-sync'></i> Refresh Grid")
        .HtmlAttributes(new { id = "companyRefresh", title = "Refresh the data in the grid." }))
    .ToolBar(toolbar => toolbar.Custom().Text("<i class='fas fa-minus-square'></i> Clear Filters")
        .HtmlAttributes(new { id = "companyReset", title = "Clear the grid column filters." }))
    .ToolBar(toolbar => toolbar.Custom().Text("<i class='fas fa-file-excel'></i> Export To Excel")
        .HtmlAttributes(new { id = "export", title = "Export to Excel", @class = "k-button k-button-icontext k-grid-excel" }))
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Pageable(pageable => pageable
        .Input(true)
        .Numeric(false)
        .PageSizes(true)
        .Messages(messages => messages.Display("Showing items from {0:0,0} to {1:0,0}. Total items: {2:0,0}"))
        .Messages(messages => messages.Empty("No companies found."))
        .PageSizes(new[] { 5, 10, 25, 50 })
    )
    .Resizable(resizeable => resizeable.Columns(true))
    .Sortable()
    .Scrollable(s => s.Height("auto"))
    .Filterable()
    .Excel(excel => excel
        .AllPages(true)
        .Filterable(true)
        .FileName("Companies.xlsx")
        .ProxyURL(Url.Action("Excel_Export_Save", "Grid"))
    )
    .Events(events => events.ExcelExport("excelExport1"))
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(r => r.Url("/Admin/Companies?handler=Read"))
        .Update(u => u.Url("/Admin/Companies?handler=Update"))
        .Create(c => c.Url("/Admin/Companies?handler=Create"))
        .Model(m =>
        {
            m.Id(id => id.InstallerCompanyId);
            m.Field(i => i.CompanyName);
            m.Field(i => i.WebSite);
            m.Field(i => i.Active).DefaultValue(true);
        })
        .PageSize(10)
        .Sort(sortable => sortable.Add("CompanyName"))
        .Events(events => events.Error("gridErrorHandler"))
    )
)

 

My JavaScript

$(function () {
    // razor pages have built in anti-forgery token so wire up the kendo grid to pass it when doing crud
    var grid = $("#CompaniesGrid").data("kendoGrid");
    grid.dataSource.transport.options.read.beforeSend = function (req) {
        req.setRequestHeader('RequestVerificationToken', $('input:hidden[name="__RequestVerificationToken"]').val());
    };
    grid.dataSource.transport.options.update.beforeSend = function (req) {
        req.setRequestHeader('RequestVerificationToken', $('input:hidden[name="__RequestVerificationToken"]').val());
    };
    grid.dataSource.transport.options.create.beforeSend = function (req) {
        req.setRequestHeader('RequestVerificationToken', $('input:hidden[name="__RequestVerificationToken"]').val());
    };
});

 

My controller method

[HttpPost]
public ActionResult Excel_Export_Save(string contentType, string base64, string fileName)
{
    var fileContents = Convert.FromBase64String(base64);
    return File(fileContents, contentType, fileName);
}

 

John
Top achievements
Rank 1
 answered on 22 May 2019
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?