Telerik Forums
UI for ASP.NET Core Forum
1 answer
44 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
639 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
154 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
9 answers
72 views

I'm using remote binding, but not appears arrow to expand node.

This is method

public JsonResult Read_DropDownTreeNewCustomerCategoriesData(string Code)
        {
            var result = GetHierarchicalNewCustomerCategoryData()
                .Where(x => !string.IsNullOrEmpty(Code) ? x.ParentCode == Code : x.ParentCode == null)
                .Select(item => new
                {
                    Code = item.Code,
                    Name = item.Name,
                    hasChildren = item.HasChildren
                });
 
            return Json(result.ToList());
        }

This is control

@(Html.Kendo().DropDownListFor(model=>model.NewCustomerCategoryCode)
                        .DataTextField("Name")
                        .DataValueField("Code")
                        .DataSource(dataSource => dataSource
                            .Read(read => read
                                .Action("Read_DropDownTreeNewCustomerCategoriesData", "ListBox")
                            )
                        )
                    )

 I attached result

Aleksandar
Telerik team
 answered on 27 Jul 2020
7 answers
82 views

I am trying to have a treelist with the new functionality and the drag&drop functionality.

I have enabled the drag&drop functionality but the treelist does not update the relationship after the drop ends.

On another post it was suggested to set Autosync on the datasource. However this creates the problem that when creating a new item it is automatically saved without the user been able to enter values first. This is not acceptable for my situation because there are some fields that are mandatory and I do not want to use a default value. So Autosync is out of the question.

On another post it was suggested to handle the DragEnd and call manually the sync on the datasource. However this is not handle as expected. Because my method sometimes should fail (The datasource error event is called). And after the error event is handled the treelist is in an incorect state since the dragged item is displayed with the wrong parent (In the Autosync if an error occured the drop would be canceled and the item returns to the initial position)

So my question is how can I have the two functionalities? (Autosync-ing only drag&drop and leave the create without autosync)

 

Tsvetomir
Telerik team
 answered on 23 Jul 2020
4 answers
404 views

Hello,

I have scheduler that has editable events. When editing an event the template that i provide loads up another scheduler. The scheduler within the editor template needs to have it's date set to match the start date of the event i'm editing. So far i can get this working by using a custom binder to bind my date in the editor model to my scheduler.

EditorTemplate:

 

 

@(Html.Kendo().Scheduler<TaskViewModel>()
    .Name("staffAvailability")
    .Height(300)
    .HtmlAttributes(new {data_bind = "bindDate:start, visible:Staff.length" })
    .Timezone("Europe/London")
    .Editable(false)
    .AutoBind(false)
    .Views(views =>
    {
        views.TimelineView(timeline =>
        {
            timeline.Footer(false);
        });
    })
    .DataSource(dataSource => dataSource
        .ServerOperation(true)
        .Read(read => read.Action("ListStaffSessions", "Scheduler").Data("getStaffAttendance"))
    ).Events(e => e.DataBound("dataBoundAttendanceControl").DataBinding("dataBindingAttendanceControl"))
    )

javascript:

kendo.data.binders.widget.bindDate = kendo.data.Binder.extend({
    init: function (widget, bindings, options) {
        kendo.data.Binder.fn.init.call(this, widget.element[0], bindings, options);
    },
    refresh: function () {
        var that = this,
            value = that.bindings["bindDate"].get()
        var scheduler = $(that.element).data("kendoScheduler");
        scheduler.date(value);
    }
});

 

The issue i have is i don't want the scheduler to read from my data source on load, so i've specified that autoBind should be false on this scheduler however because i'm trying to bind the date this way that results in a change event being fired and my data source gets read.

Is there any way for me to provide the scheduler in my editor template a start date via the html helpers to avoid having to write a custom binder?

Aleksandar
Telerik team
 answered on 23 Jul 2020
2 answers
141 views

Hi,
I've created a grid to with i've added several dropdowns as editor controls I have added the relevant UIHints etc... and the drop downs are shoing and being populated correctly however when selecting a value from one of the dropdows I get an error that shows up in the console complaining that the property is null and when the model is passed through to the update method the values being passed are those of the original data and not the updated fields 
This is my grid:

@(
        Html.Kendo().Grid<BookingHub.Areas.Admin.ViewModels.DriverTestTypeViewModel>
        ()
        .Name("DrivingTestTypesGrid")
        .Columns(columns => {
        columns.Bound(t => t.Name).Title("Category Name");
        columns.Bound(t => t.Description).Title("Description");
        columns.Bound(t => t.Duration).Title("Duration");
        columns.Bound(t => t.StandardFee).Title("Standard Fee");
        columns.Bound(t => t.PremiumFee).Title("Premium Fee");
        columns.Bound(t => t.TheoryTestCode).Title("Theory Test Required")
        .ClientTemplate("#= TheoryTestCode == null? '' : TheoryTestCode.Description  #");
        columns.Bound(t => t.FullTestRequired).Title("Full Test Required")
            .ClientTemplate("#= FullTestRequired == null? '' : FullTestRequired.Category  #");
        columns.Command(command => {
        command.Edit().Template("<a title='Click to edit' class='k-button k-button-icontext btn btn-sm k-secondary k-grid-edit'><i class='fa fa-pencil-alt text-primary'></i></a>");
        command.Custom("UpdateFee").Click("").Template("<a title='Click to edit' class='k-button k-button-icontext btn btn-sm k-secondary' data-toggle='modal'><i class='fa fa-pencil-alt text-primary'></i></a>");
            });
        })
        .Editable(editable => editable.Mode(GridEditMode.InLine))
        .Pageable()
        .Sortable()
        .DataSource(dataSource => dataSource
                    .Ajax()
                    .PageSize(15)
                    .AutoSync(false)
                    .ServerOperation(false) //paging, sorting and grouping performed in the client
                    .Events(events => events.Error("GenericErrorHandler.handleCoreErrors('#DrivingTestTypesGrid')"))
                    .Model(model =>
                    {
                        model.Id(p => p.Id);
                        model.Field(p => p.Name);
                        model.Field(t => t.Description);
                        model.Field(t => t.Duration);
                        model.Field(t => t.StandardFee);
                        model.Field(t => t.PremiumFee);
                        model.Field(t => t.TheoryTestCode);
                        model.Field(t => t.FullTestRequired).DefaultValue(ViewData["DriverTestTypesDefault"] as BookingHub.Areas.Admin.ViewModels.FullTestRequiredViewModel );
                    })
                    //.Create("CreateCustomerAccount", "View", new { Area = "Admin" })
                    .Read("GetDriverTestTypes", "DriverTestTypes", new { Area = "Admin" })//.Type(HttpVerbs.Post))
                    .Update("UpdateDriverTestType", "DriverTestTypes", new { Area = "Admin" })
                    //.Destroy("DeactivateCustomerAccount", "View", new { Area = "Admin" })
 
                    )
    )

 

My View Model : 

public class DriverTestTypeViewModel : GenericViewModel
    {
        [ScaffoldColumn(false)]
        public int Id { get; set; }
        [UIHint("TextArea")]
        public string Description { get; set; }
        public int Duration { get; set; }
        [Display(Name = "Start Date")]
        public DateTime StartDate { get; set; }
        [Display(Name = "End Date")]
        public DateTime? EndDate { get; set; }
        [ScaffoldColumn(false)]
        public string CreatedBy { get; set; }
        [ScaffoldColumn(false)]
        public DateTime? CreatedOn { get; set; }
        [ScaffoldColumn(false)]
        public string UpdatedBy { get; set; }
        [ScaffoldColumn(false)]
        public DateTime? UpdatedOn { get; set; }
        public string Name { get; set; }
        [DataType(DataType.Currency)]
        public decimal StandardFee { get; set; }
        [DataType(DataType.Currency)]
        public decimal PremiumFee { get; set; }
        [UIHint("TheoryTestCodeEditor")]
        public TheoryTestCodeViewModel? TheoryTestCode { get; set; }
        [UIHint("FullTestRequiredEditor")]
        public FullTestRequiredViewModel? FullTestRequired { get; set; }
        public int? TheoryTestTypeId { get; set; }
    }

 

My editor controls (obviously in separate partial views named the same as the ui hint):

@(Html.Kendo().DropDownList()
        .Name("FullTestRequired") // The name of the widget has to be the same as the name of the property.
        .DataValueField("Id") // The value of the drop-down is taken from the TheoryTestCode Id property.
        .DataTextField("Category") // The text of the items is taken from the TheoryTestCodes Description property.
        .BindTo((System.Collections.IEnumerable)ViewData["DriverTestTypes"]) // A list of all TheoryTestCodes which is populated in the controller.
        .AutoBind(false)
)
@(Html.Kendo().DropDownList()
    .Name("TheoryTestCode") // The name of the widget has to be the same as the name of the property.
    .DataValueField("Id") // The value of the drop-down is taken from the TheoryTestCode Id property.
    .DataTextField("Description") // The text of the items is taken from the TheoryTestCodes Description property.
    .BindTo((System.Collections.IEnumerable)ViewData["TheoryTestCodes"]) // A list of all TheoryTestCodes which is populated in the controller.
    .AutoBind(false)
)

 

The following is where i populate the dropdowns :

public async Task<ActionResult> Index()
       {
 
           ViewData["TheoryTestCodes"] = new List<TheoryTestCodeViewModel> {
               new TheoryTestCodeViewModel { Description = "MotorBike", Id = 2, TestCode = 2 },
               new TheoryTestCodeViewModel { Description = "Car", Id = 1, TestCode = 1 }
           };        
 
           ViewData["DriverTestTypes"] = new List<FullTestRequiredViewModel>
           {
               new FullTestRequiredViewModel { Category = "A1 Off Road", Id = 2 },
               new FullTestRequiredViewModel { Category = "Test", Id = 3 }
           };
 
           ViewData["DriverTestTypesDefault"] = new List<FullTestRequiredViewModel>
           {
               new FullTestRequiredViewModel { Category = "A1 Off Road", Id = 2 }
           };
 
           return this.View("DriverTestType");
       }

 

The console error that is displaying is "Uncaught TypeError: Cannot read property 'FullTestRequired' of null" which happen on the selection of an item from the dropdown

 

I can't see what is wrong so any assistance would be gratefully appreciated :) 

Tsvetomir
Telerik team
 answered on 23 Jul 2020
3 answers
306 views

When I add an editor to a form either directly or through the new wizard, it does not unmask the field. Please let me know what am I doing wrong.

...
    item.Add()
        .Field(field => field.Zip)
        .Label(label => label.Text("Zip"))
        .Editor(editor => editor.MaskedTextBox().Mask("00000-9999").UnmaskOnPost());
...
Aleksandar
Telerik team
 answered on 22 Jul 2020
1 answer
402 views

I am trying to use either the new Form or Wizard widget as a popup editor, but it does not bind the data item to the widget.
Is this supported? Is there a way I can archive this?

Thanks

Aleksandar
Telerik team
 answered on 22 Jul 2020
6 answers
239 views
Hello, how are you?
I'm from Brazil, very pleased.

So, I want to press delete, delete also on my backend, not only on my client, I used the destroy method, but it only deletes on the client, it is not deleting from my DB, anyway, where am I wrong?

public IActionResult Delete(Guid? id, [DataSourceRequest] DataSourceRequest request)
        {
            try
            {
                var game = UnitOfWork.Game.Get(id);
                UnitOfWork.Game.Delete(game);
                UnitOfWork.SaveChanges();

                return Json(game, request);
            }
            catch (Exception e)
            {
                throw new ArgumentException(e.Message);
            }

        }

And now my Grid:

@(Html.Kendo().Grid<GameListViewModel>()
      .Name("Grid")
      .Columns(columns =>
      {
          columns.Bound(p => p.Name).Title("Nome");
          columns.Bound(p => p.Price).Title("Preço");
          columns.Bound(p => p.Description).Title("Descrição");
          columns.Bound(p => p.GenderName).Title("Categoria");
          columns.Command(c => c.Edit().HtmlAttributes(new {title = "Editar Item"})).Title("Editar");
          columns.Command(read => read.Destroy().HtmlAttributes(new {title = "Deletar item"})).Title("Deletar");
      })
      .Pageable()
      .Sortable()
      .Scrollable()
      .Filterable()
      .HtmlAttributes(new { style = "height:430px;" })
      .DataSource(dataSource => dataSource
          .Ajax()
          .PageSize(20)
          .Read(read => read.Action("TelerikGrid", "Game"))
          .Update(read => read.Action("Edit", "Game", new {id = "{0}"}))
          .Destroy(read => read.Action("Delete", "Game"))
      ))

Probably my call is not going to the controller, how can I resolve it? Thank you.
Tsvetomir
Telerik team
 answered on 21 Jul 2020
Narrow your results
Selected tags
Tags
+? more
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Jay
Top achievements
Rank 3
Bronze
Iron
Iron
yw
Top achievements
Rank 2
Iron
Iron
Stefan
Top achievements
Rank 2
Iron
Iron
Iron
Kao Hung
Top achievements
Rank 1
Iron
Bohdan
Top achievements
Rank 2
Iron
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?