Telerik Forums
UI for ASP.NET Core Forum
1 answer
1.9K+ views

I am trying to achieve inline insertion in a grid with client side code. I am using tag helper and generating toolbar with custom button and binding click event with javaScript function. And through this function I need to achieve functionality of "Create" button under grid's toolbar option. 

To elaborate the things, there are two toolbar one is "kindo-toolbar" and another is "toolbar" under "kendo-grid". Toolbar under kendo-grid is having "Add new record" button and on click on this button generates new blank row in grid to add new record. This same functionality I need to achieve through "Kendo-toolbar" item button, where I can bind a click event with a javascript function. So is there a way to implement inline row adding with toolbar item with javascript or any other approach?

<div class="demo-section k-content wide">
        <kendo-toolbar name="ToolBar">
            <toolbar-items>
                <item type="CommandType.Button" icon="add" text="" click="buttonClick" />               
            </toolbar-items>
        </kendo-toolbar>
    </div>
 
<kendo-grid name="grid" height="550">
    <datasource page-size="20" type="DataSourceTagHelperType.Custom" custom-type="odata" batch="true">
        <transport>
        </transport>
        <schema>
            <model id="ProductID">
                <fields>
                    <field name="ProductName"></field>
                    <field name="UnitPrice" type="number"></field>
                    <field name="UnitsInStock" type="number"></field>
                </fields>
            </model>
        </schema>
    </datasource>
    <editable mode="incell" />
    <pageable button-count="5" refresh="true" page-sizes="new int[] { 5, 10, 20 }">
    </pageable>
     
    <toolbar>
        <toolbar-button name="create" text="Add new record"></toolbar-button>
        <toolbar-button name="save" text="Save Changes"></toolbar-button>
        <toolbar-button name="cancel" text="Cancel Changes"></toolbar-button>
         
    </toolbar>
     
    <columns>
        <column field="ProductName" title="Product Name" width="240" />
        <column field="UnitPrice" title="Unit Price" />
        <column field="UnitsInStock" title="Units In Stock" />
        <column field="Discontinued" title="Discontinued" width="150" />
        <column>
            <commands>
                <column-command text="Delete" name="destroy"></column-command>
            </commands>
        </column>
    </columns>
</kendo-grid>
 
<script>
    function buttonClick(e) {       
        alert("Button Clicked");
    }
</script>

 

Eyup
Telerik team
 answered on 18 Oct 2019
3 answers
1.5K+ views

I am having dockerized Asp.Net Core application and using telerik UI for Asp.Net Core licensed NuGet Package by creating Telerik Package Source with physical path on my disk for nupkg file. All development was going well in debug mode, but when I tried to make a release, its giving the error - Unable to find package Telerik.UI.for.AspNet.Core with version >= 2018.2.620. Then it says that Found 1 version in nuget.org with Version 2016.3.914. 

I don't think I should use this older version from nuget.org and moreover I will get trial version there.

Please suggest, if I am missing some steps to reference it properly.

Ianko
Telerik team
 answered on 17 Oct 2019
3 answers
2.5K+ views

Hi,

I'm using Kendo professional for Asp.net Core.

I got the error in "Session.GetObjectFromJson<IList< " and "Session.SetObjectAsJson( "

SeverityCodeDescriptionProjectFileLineSuppression State
ErrorCS1061'ISession' does not contain a definition for 'GetObjectFromJson' and no accessible extension method 'GetObjectFromJson' accepting a first argument of type 'ISession' could be found (are you missing a using directive or an assembly reference?)

I tried to fix by install Session from Nuget. but I can't find any package called Session in Nuget.  Thank you if you can help.

 

ProductService.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Http;
using Kendo.Mvc.Examples.Extensions;

namespace Kendo.Mvc.Examples.Models
{
public class ProductService : BaseService, IProductService
    {
        private static bool UpdateDatabase = false;
        private ISession _session;

        public ISession Session { get { return _session; } }

        public ProductService(IHttpContextAccessor httpContextAccessor)
        {
            _session = httpContextAccessor.HttpContext.Session;
        }

        public IEnumerable<ProductViewModel> Read()
        {
            return GetAll();
        }

        public IList<ProductViewModel> GetAll()
        {
            using (var db = GetContext())
            {
                var result = Session.GetObjectFromJson<IList<ProductViewModel>>("Products");

                if (result == null || UpdateDatabase)
                {
                    var categories = db.Categories.ToList();

                    result = db.Products.ToList().Select(product =>
                    {
                        var category = categories.First(c => product.CategoryID == c.CategoryID);

                        return new ProductViewModel
                        {
                            ProductID = product.ProductID,
                            ProductName = product.ProductName,
                            UnitPrice = product.UnitPrice.HasValue ? product.UnitPrice.Value : default(decimal),
                            UnitsInStock = product.UnitsInStock.HasValue ? product.UnitsInStock.Value : default(int),
                            QuantityPerUnit = product.QuantityPerUnit,
                            Discontinued = product.Discontinued,
                            UnitsOnOrder = product.UnitsOnOrder.HasValue ? product.UnitsOnOrder.Value : default(int),
                            CategoryID = product.CategoryID,
                            Category = new CategoryViewModel()
                            {
                                CategoryID = category.CategoryID,
                                CategoryName = category.CategoryName
                            },
                            LastSupply = DateTime.Today
                        };
                    }).ToList();

                    Session.SetObjectAsJson("Products", result);
                }

                return result;
            } 
        }

        public void Create(ProductViewModel product)
        {
            if (!UpdateDatabase)
            {
                var products = GetAll();
                var first = products.OrderByDescending(e => e.ProductID).FirstOrDefault();
                var id = (first != null) ? first.ProductID : 0;

                product.ProductID = id + 1;

                products.Insert(0, product);

                Session.SetObjectAsJson("Products", products);
            }
            else
            {
                using (var db = GetContext())
                {
                    var entity = new Product();

                    entity.ProductName = product.ProductName;
                    entity.UnitPrice = product.UnitPrice;
                    entity.UnitsInStock = (short)product.UnitsInStock;
                    entity.Discontinued = product.Discontinued;
                    entity.CategoryID = product.CategoryID;

                    if (entity.CategoryID == null)
                    {
                        entity.CategoryID = 1;
                    }

                    if (product.Category != null)
                    {
                        entity.CategoryID = product.Category.CategoryID;
                    }

                    db.Products.Add(entity);
                    db.SaveChanges();

                    product.ProductID = (int)entity.ProductID;
                }
            }
        }

        public void Update(ProductViewModel product)
        {
            if (!UpdateDatabase)
            {
                var products = GetAll();
                var target = products.FirstOrDefault(e => e.ProductID == product.ProductID);

                if (target != null)
                {
                    target.ProductName = product.ProductName;
                    target.UnitPrice = product.UnitPrice;
                    target.UnitsInStock = product.UnitsInStock;
                    target.Discontinued = product.Discontinued;
                    target.CategoryID = product.CategoryID;
                    target.Category = product.Category;
                }

                Session.SetObjectAsJson("Products", products);
            }
            else
            {
                using (var db = GetContext())
                {
                    var entity = new Product();

                    entity.ProductID = product.ProductID;
                    entity.ProductName = product.ProductName;
                    entity.UnitPrice = product.UnitPrice;
                    entity.UnitsInStock = (short)product.UnitsInStock;
                    entity.Discontinued = product.Discontinued;
                    entity.CategoryID = product.CategoryID;

                    if (product.Category != null)
                    {
                        entity.CategoryID = product.Category.CategoryID;
                    }

                    db.Products.Attach(entity);
                    db.Entry(entity).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
        }

        public void Destroy(ProductViewModel product)
        {
            if (!UpdateDatabase)
            {
                var products = GetAll();
                var target = products.FirstOrDefault(e => e.ProductID == product.ProductID);

                if (target != null)
                {
                    products.Remove(target);
                }

                Session.SetObjectAsJson("Products", products);
            }
            else
            {
                using (var db = GetContext())
                {
                    var entity = new Product();

                    entity.ProductID = product.ProductID;

                    db.Products.Attach(entity);

                    db.Products.Remove(entity);

                    var orderDetails = db.OrderDetails.Where(pd => pd.ProductID == entity.ProductID);

                    foreach (var orderDetail in orderDetails)
                    {
                        db.OrderDetails.Remove(orderDetail);
                    }

                    db.SaveChanges();
                }
            }
        }
    }
}

Viktor Tachev
Telerik team
 answered on 16 Oct 2019
12 answers
2.2K+ views

Hello,

How to reload a timeline (with Kendo grid I can use grid.dataSource.read();)

robert

Robert Madrian
Top achievements
Rank 1
Veteran
Iron
 answered on 16 Oct 2019
5 answers
1.1K+ views

Hi,

We've just bought the UI for ASP.NET Core components and have started using the Grid component in our ASP.NET Core 2.1 project. From what I understand, unlike the ASP.NET MVC grid, the ASP.NET Core grid is not a true server-side component and the Html and TagHelpers are basically just wrappers for the Kendo UI for jQuery client-side javascript based component, right?

If that's the case then what is the best way to implement server-side formatting/rendering of certain data in the columns of the grid? Until now we've used normal html tables and put our custom TagHelpers and text formatting functions calls directly in the cells of those tables (in the .cshtml files). For example we have a custom class that wraps an integer and converts that value to minutes and various other things.

I've noticed there is the ClientTemplate of the columns in the grid but you can't put TagHelpers or .ToString() methods in those templates since they are just evaluated in javascript on the client.

Is there a way to use the MVC grid in Core projects?

/Marcus

 

Angel Petrov
Telerik team
 answered on 15 Oct 2019
3 answers
354 views

Hallo zusammen,

ich habe in meinem Grid zwei Knöpfe, die das edit event auslösen. Ich rufe damit das gleiche Popup auf, aber abhängig davon welcher Edit button geklickt wurde, müssen im Popup verschiedene Elemente ein- oder ausgeblendet werden. Ich habe noch keine Möglichkeit gefunden wie ich herausbekomme welcher Knopf geklickt wurde.

Beide Button befinden sich in der Toolbar
        .ToolBar(t =>
        {
            t.Create().Text("Add User");
            t.Create().Text("Add Host");
        }
 und das Event folgendermaße deklariert:
        .Events(events => events
            .Edit("insertPopupCaption")
        )

Kann mir hier bitte jemand weiterhelfen?

Kind regards
Markus

Markus
Top achievements
Rank 1
 answered on 15 Oct 2019
2 answers
1.0K+ views

Hi

please help me how to use Kendo Editor Template

this is my code:

Product Model:

[UIHint("RichText")]
 
public string ProductDescription { get; set; }

 

RichText EditorTemplate

@model string
 
@* Make sure tag helpers are not available for the Editor content *@
@removeTagHelper "*, Microsoft.AspNet.Mvc.Razor"
@removeTagHelper "*, Microsoft.AspNetCore.Mvc.Razor"
 
@(Html.Kendo().EditorFor(mo => mo).Encoded(false)
          .Name("editor")
          .HtmlAttributes(new { style = "height:440px", aria_label = "editor" })
          .Resizable(resizable => resizable.Content(true).Toolbar(true))
          .ImageBrowser(imageBrowser => imageBrowser
              .Image("~/Shared/UserFiles/Images/{0}")
              .Read("Read", "ImageBrowser")
              .Create("Create", "ImageBrowser")
              .Destroy("Destroy", "ImageBrowser")
              .Upload("Upload", "ImageBrowser")
          )
 
    )

 

usage in View:

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

 

but I get Error below:

An unhandled exception occurred while processing the request.
InvalidOperationException: You cannot override component name when bound to a model expression.
Kendo.Mvc.UI.Fluent.WidgetBuilderBase<TViewComponent, TBuilder>.Name(string componentName)

 

 

InvalidOperationException: You cannot override component name when bound to a model expression.
Kendo.Mvc.UI.Fluent.WidgetBuilderBase<TViewComponent, TBuilder>.Name(string componentName)
AspNetCore.Views_Shared_EditorTemplates_RichText.ExecuteAsync() in RichText.cshtml
+
@(Html.Kendo().EditorFor(mo => mo)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.TemplateRenderer.Render()
Microsoft.AspNetCore.Mvc.ViewFeatures.TemplateBuilder.Build()
Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper.GenerateEditor(ModelExplorer modelExplorer, string htmlFieldName, string templateName, object additionalViewData)
Microsoft.AspNetCore.Mvc.ViewFeatures.HtmlHelper<TModel>.EditorFor<TResult>(Expression<Func<TModel, TResult>> expression, string templateName, string htmlFieldName, object additionalViewData)
Microsoft.AspNetCore.Mvc.Rendering.HtmlHelperEditorExtensions.EditorFor<TModel, TResult>(IHtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TResult>> expression)
AspNetCore.Areas_Users_Views_Products_Edit.<ExecuteAsync>b__24_0() in Edit.cshtml
+
                @Html.EditorFor(m => m.ProductDescription)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
AspNetCore.Areas_Users_Views_Products_Edit.ExecuteAsync() in Edit.cshtml
+
    Layout = "~/Areas/Users/Views/Shared/_Layout.cshtml";
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultAsync>g__Logged|21_0(ResourceInvoker invoker, IActionResult result)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Ivan Danchev
Telerik team
 answered on 15 Oct 2019
0 answers
78 views
Do all Control components support Razor Pages development mode?
ghd258 ghd258
Top achievements
Rank 1
 asked on 14 Oct 2019
1 answer
1.2K+ views

Hi,

I'm using Telerik for ASP .NET Core and I have a model with a column that is a list.

1.columns.Bound(p => p.Actions)
2..ClientTemplate("#= actionsTemplate(data) #");

 

The client template, which is generated correctly:

01.function actionsTemplate(item) {
02.  let template = "";
03.  for(var i=0; i< item.Actions.length; i++){
04.     let action = item.Actions[i];
05.     template += kendo.format("<button class='btn btn-block btn-outline-success btn-sm action'" +
06.      "onclick='showDetails(this)' data-url='{0}' data-allowedState='{1}'>{2}</button>",
07.       action.Url, action.AllowedState, action.Title);
08.   }
09.   return template;
10.}

 

Then when I click a button in the column, I want to display a form, with 2 buttons, one that makes a POST, one that cancels/closes the form:

01.let detailsTemplate = kendo.template($("#template").html());
02. 
03.function showDetails(e) {
04.    e.preventDefault();
05. 
06.    let row = $(e).closest("tr");
07.    let closest = $(e.currentTarget).closest("tr");
08.    let dataItem = this.dataItem(closest);
09. 
10.    let wnd = $("#action").data("kendoWindow");
11. 
12.    wnd.content(detailsTemplate(dataItem));
13.    wnd.center().open();
14.}

 

The template:

01.<script type="text/x-kendo-template" id="template">
02.    <form action="#= Url #" method="post">
03.        <div id="action-container">
04.            <h2>#= Title # </h2>
05. 
06.            Do you want to perform #= Action # for #= Title # ?
07.        </div>
08.        <button type="submit" class="btn btn-primary">Yes</button>
09.        <button type="reset" class="btn btn-default float-right">No</button>
10.    </form>
11.</script>

 

The problem is that in showDetails() function, I get an error on line 8:

 this.dataItem is not a function.

Also, e.currentTarget is undefined, but $(e).closest("tr") is the containing tr element.

 

 How can I achieve this functionality?

Martin
Telerik team
 answered on 11 Oct 2019
1 answer
343 views

I have a Grid with an editable DateTime field. What happens is when I type in a date, if it doesn't adhere to the Format statement, it clears the field when I hit tab. What I want is if I enter something like 01012020, I want to try and parse it in javascript and get a valid date to use. I have tried using OnBlur, but that never gets called. The onDateChange function has null for the value of that field. I think it's already cleared it out.

The grid defines the field and the editor template as,

.Columns(proposed =>
{
proposed.Bound(prop => prop.DateProposed).Editable("true").EditorTemplateName("SelectDateDD").Format("{0:MM/dd/yyyy}").Title("Date").Width(113);
}

SelectDateDD:

@(Html.Kendo().DatePickerFor(m => m).Events(e=>e.Change("onDateChange")))

Tsvetomir
Telerik team
 answered on 10 Oct 2019
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?