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

Hello,

I saw an example by you guys for razor pages but I need it done for CRUD operations for a data source in the sql server. Assume I have appsettings.json file setup with the correct sql server connection string along with ApplicationDBContext setup in the startup.cs file in the configureservices section to allow dependency injection and the ApplicationDBContext was passed through a constructor for the specified model referenced in the code below to utilize dependency injection. What else would I need to change in the code to allow me to do CRUD operations on razor pages that utilizes entity framework core sql server as its data source?


@page
@model Telerik.Examples.RazorPages.Pages.Grid.GridCrudOperationsModel
@{
    ViewData["Title"] = "GridCrudOperations";
}

<h1>GridCrudOperations</h1>

@using Telerik.Examples.RazorPages.Models
@using Kendo.Mvc.UI

@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@Html.AntiForgeryToken()

@(Html.Kendo().Grid<OrderViewModel>().Name("grid")
                .Groupable()
                .Sortable()
                .Editable()
                .Scrollable()
                .ToolBar(x => {
                    x.Create();
                    x.Excel();
                })
                .Columns(columns =>
                {
                    columns.Bound(column => column.Freight);
                    columns.Bound(column => column.ShipName);
                    columns.Bound(column => column.ShipCity);
                    columns.Command(column =>
                    {
                        column.Edit();
                        column.Destroy();
                    });
                })
                 .Excel(excel => excel
                            .FileName("Export.xlsx")
                            .Filterable(true)
                            .ProxyURL("/Grid/GridCrudOperations?handler=Save")
                        )
                .DataSource(ds => ds.Ajax()
                       .Read(r => r.Url("/Grid/GridCrudOperations?handler=Read").Data("forgeryToken"))
                       .Update(u => u.Url("/Grid/GridCrudOperations?handler=Update").Data("forgeryToken"))
                       .Create(c => c.Url("/Grid/GridCrudOperations?handler=Create").Data("forgeryToken"))
                       .Destroy(d => d.Url("/Grid/GridCrudOperations?handler=Destroy").Data("forgeryToken"))
                       .Model(m => m.Id(id => id.OrderID))
                    .PageSize(10)
                )
                .Pageable()
)

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

 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Telerik.Examples.RazorPages.Models;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace Telerik.Examples.RazorPages.Pages.Grid
{
    public class GridCrudOperationsModel : PageModel
    {
        public static IList<OrderViewModel> orders;

        public void OnGet()
        {
            if (orders == null)
            {
                orders = new List<OrderViewModel>();

                Enumerable.Range(0, 50).ToList().ForEach(i => orders.Add(new OrderViewModel
                {
                    OrderID = i + 1,
                    Freight = i * 10,
                    ShipName = "ShipName " + i,
                    ShipCity = "ShipCity " + i
                }));

            }
        }

        public JsonResult OnPostRead([DataSourceRequest] DataSourceRequest request)
        {
            return new JsonResult(orders.ToDataSourceResult(request));
        }

        public JsonResult OnPostCreate([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            order.OrderID = orders.Count + 2;
            orders.Add(order);

            return new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState));
        }

        public JsonResult OnPostUpdate([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            orders.Where(x => x.OrderID == order.OrderID).Select(x => order);

            return new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState));
        }

        public JsonResult OnPostDestroy([DataSourceRequest] DataSourceRequest request, OrderViewModel order)
        {
            orders.Remove(orders.FirstOrDefault(x => x.OrderID == order.OrderID));

            return new JsonResult(new[] { order }.ToDataSourceResult(request, ModelState));
        }

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

            return File(fileContents, contentType, fileName);
        }
    }
}

 

Aleksandar
Telerik team
 answered on 31 May 2021
1 answer
296 views
Why the AdditionalFields are not passed along in the validation when InCell mode? SO question here
Mihaela
Telerik team
 answered on 27 May 2021
1 answer
2.1K+ views

I have a simple grid setup with the datasource is returning a list.

  <kendo-grid name="grid" height="550">
      <datasource type="DataSourceTagHelperType.WebApi" page-size="5">
          <transport>
               <read url="@Url.Action("GetSchedule", "Home")" />
          </transport>
      </datasource>
      <columns>
           <column field="SalesRepName" title="Sales Agent" />               
           <column field="Shift" title="Shift" />
           <column field="Phone" title="Phone" />
      </columns>
 </kendo-grid>

  public ActionResult GetSchedule([DataSourceRequest] DataSourceRequest request)
        {
            // get scheduled sales rep.
            var result = _idb.RetrieveCurrentSchedule("LSL", "NH");

            var dsResult = result.ToDataSourceResult(request);

            return Json(dsResult);

        }
bundle.js:1 Uncaught TypeError: Cannot read property 'slice' of undefined

 

Mihaela
Telerik team
 answered on 26 May 2021
1 answer
97 views

I am trying to aggregate my chart data but having no luck, I can do this using jqery version but not the .net core verion.

date is coming from a view model:
DataValue
DataCategory
DataColour

I have multiple entries so I need to sum the DataCategory up.

Ive been trying aggregates.Add and groups.add to the data source but ive had no luck getting the chart to display correctly.

@(Html.Kendo().Chart(Model.ChartSetup)
            .Name(@"ChartName")

            .Series(series =>
            {

                series.Donut(model => model.DataValue, categoryExpression: model => model.DataCategory).ColorField("DataColour")

             .Overlay(o => o.Gradient(ChartSeriesGradient.None))

                .Labels(labels => labels
                .Position(ChartBarLabelsPosition.OutsideEnd)

                .Visible(false)

                      .Template("#= category # - #= kendo.format('{0:P}', percentage)#")
                );
            })


            )
Aleksandar
Telerik team
 answered on 26 May 2021
1 answer
113 views

I have a Grid with Popup Edit.

In the popup, there is a  required combobox, that should be selected only in Create mode. But in Edit mode, the selected combo value should be readonly. How to implement that logic? 

Tsvetomir
Telerik team
 answered on 26 May 2021
1 answer
799 views

Hello,

I bought kendo UI ASP.NET Core and i using it in my asp net core project.

i want to use kendo ui map in my project and i use tile layer like this

 

 layers: [{
                            type: "bing", // this layer is the map  , layer[0]
                            imagerySet: "aerialWithLabels",

                            key: "h0yO0NtadB4lkxJAaBhO~9ZxiGd8wv3tE3MGtwDCVaQ~AvJmJR3vegm0gJw6grYJ2OnnVtgMio1FeEMb4mMBKU2qmxvtIZxx7Hl-rAasXWSH"
                        }

 

the key is my key from microsoft bing map.

 

my question:

i want to use the map without internet connection . i have rastar map on local file in my computer and i want to use this map or bing map offline without internet

 

is it possible? and how can i do this? i try many guide in the site and i just cant understand what is wrong.

Tsvetomir
Telerik team
 answered on 25 May 2021
0 answers
475 views
In the editor, when you click create link it shows http in the text box. Our customer would like that to be https:// by default. How can I change this? I've using Tag Helpers.
Scott
Top achievements
Rank 1
 asked on 24 May 2021
1 answer
125 views

I have attached the exact error message after migrating to core, some of the chart in Kendo is not working. 

Please advise if this related to the kendo version or code config change with core?

Thanks

Georgi
Telerik team
 answered on 24 May 2021
9 answers
1.8K+ views

the exception is:

"Processing of the LINQ expression 'GroupByShaperExpression:
KeySelector: t.Year,
ElementSelector:EntityShaperExpression:
    EntityType: ProjectBudget
    ValueBufferExpression:
        ProjectionBindingExpression: EmptyProjectionMember
    IsNullable: False
' by 'RelationalProjectionBindingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information."

 

this happens when the DataSourceRequest contains Group, and the IQueriable items are empty

 
Carlos
Top achievements
Rank 2
Iron
Iron
Iron
 updated answer on 24 May 2021
1 answer
577 views

Hi there

I am looking at using the scheduler. I have a basic CRUD set up with it able to load data from the backend.
Currently the popup includes some fields I don't want (the "Repeat field"). I also want to add some additional fields to it.

 

Is it possible to customise the fields that appear within the popup. If I add "references" in the .net core they appear as dropdown or multi selects. But I have not found a way to specify what else should be visble/invisible.

I have a model that inherits from ISchedulerEvent

e.g


public class EventsSchedulerViewModel : ISchedulerEvent
    {
        public EventsSchedulerViewModel()
        {

        }

        public EventsSchedulerViewModel(
            long eventId,
            string title,
            string description,
            bool isAllday,
            string startTimeZone,
            string endTimeZone,
            string recurrenceRule,
            string recurrenceException,
            DateTime startDate,
            DateTime endDate,
            IEnumerable<int> events)
        {
            EventId = eventId;
            Title = title;
            Description = description;
            IsAllDay = isAllday;
            StartTimezone = startTimeZone;
            EndTimezone = endTimeZone;
            RecurrenceRule = recurrenceRule;
            RecurrenceException = recurrenceException;
            Start = startDate;
            End = endDate;
            Events = events;

        }

        public long EventId { get; set; }

        public string Title { get; set; }
        public string Description { get; set; }
        public bool IsAllDay { get; set; }
       

        public string StartTimezone { get; set; }
        public string EndTimezone { get; set; }
        public string RecurrenceRule { get; set; }
        public string RecurrenceException { get; set; }

        public bool NewField { get; set; } //New field to try and add a tick box to the popup
     
        private DateTime start;
        public DateTime Start
        {
            get
            {
                return start;
            }
            set
            {
                start = value.ToUniversalTime();
            }
        }

        private DateTime end;

        public DateTime End
        {
            get
            {
                return end;
            }
            set
            {
                end = value.ToUniversalTime();
            }
        }

        public IEnumerable<int> Events { get; set; }

    }


 

 

My guess is either there is some kind of attribute on the model to tell it to populate in the popup.

Or there is some kind of template I can use to then call on the RazorPage?

 

I was guessing adding a script for a template like:

 <script id="event-template" type="text/x-kendo-template">
        <div class="k-edit-label"><label for="title">Title</label></div>
        <div data-container-for="title" class="k-edit-field">
            <input type="text" class="k-textbox" name="title" required="required" data-bind="value:title">
        </div>
    </script>

and then in the razor doing something like 

.EventTemplateId("event-template")

Here is my View:


@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@Html.AntiForgeryToken()

@(Html.Kendo().Scheduler<FrameWow.Models.Events.Scheduler.EventsSchedulerViewModel>
    ()
    .Name("scheduler")
    .Date(DateTime.Today.Date)
    .StartTime(DateTime.Today)
    .ShowWorkHours(false)
    .Height(600)
    .Views(views =>
    {
    views.DayView();
    views.WeekView(weekView => weekView.Selected(true));
    views.MonthView();
    views.AgendaView();
    views.TimelineView();
    })
    .Timezone("Etc/UTC")
    .Resources(resource =>
    {
    resource.Add(m => m.EventId)
    .Title("Events")
    .DataTextField("Text")
    .DataValueField("Value")
    .DataColorField("Color")
    .BindTo(new[]
    {
    new { Text = "Room 1", Value = 1, Color = "#6eb3fa" },
    new { Text = "Room2", Value = 2, Color = "#f58a8a" }
    });
    resource.Add(m => m.Events)
    .Title("Events")
    //.Name("Events")
    .Multiple(true)
    .DataTextField("Text")
    .DataValueField("Value")
    .DataColorField("Color")
    .BindTo(new[]
    {
    new { Text = "Meeting 1", Value = 1, Color = "#f8a398" } ,
    new { Text = "Meeting 2", Value = 2, Color = "#51a0ed" } ,
    new { Text = "Meeting 3", Value = 3, Color = "#56ca85" }
    });
    })
    //.EventTemplateId("event-template")
    .DataSource(d => d
    .Model(m =>
    {
        m.Id(f => f.EventId);
        m.Field(f => f.Title).DefaultValue("No title");
        m.Field(f => f.Events).DefaultValue(1);
    })
    .Read(read => read.Url(Url.Page("Scheduler","ReadEventScheduler")).Data("additionalData").Type(HttpVerbs.Post))
    .Create(create => create.Url(Url.Page("Scheduler","CreateEventScheduler")).Data("additionalData").Type(HttpVerbs.Post))
    .Update(update => update.Url(Url.Page("Scheduler","UpdateEventScheduler")).Data("additionalData").Type(HttpVerbs.Post))
    .Destroy(destroy => destroy.Url(Url.Page("Scheduler","DeleteEventScheduler")).Data("additionalData").Type(HttpVerbs.Post))
    )
    )

I want to hide the "recurring" items and selection from the popup and add some of my own fields in. I have had a  look at the documentation around templates and couldn't find anything suggesting how to do this.

Any help to point me in the right direction would be appreciated.

Thanks

Phil
Top achievements
Rank 1
Veteran
Iron
 answered on 24 May 2021
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?