Telerik Forums
UI for Blazor Forum
1 answer
578 views

Is there an ETA on when the Chat control will be available?

 

Thanks, -Tim

Marin Bratanov
Telerik team
 answered on 12 May 2021
1 answer
891 views

Hi 

I am trying to recreate the design below using stacked bar charts, I want to remove all gridlines.   The red boxes are not part of the design but rather confidential info.

As you can see I have been able to remove all the gridlines and values I don't want but the vertical ones.

Here is my code,  just playing at the moment. 

  <TelerikChart Width="100%" Height="10%">
                                <ChartSeriesItems>
                                    <ChartSeries Type="ChartSeriesType.Bar" Name="Product 1" Data="@series1Data">
                                        <ChartSeriesStack Group="myStack" Type="Telerik.Blazor.ChartSeriesStackType.Stack100"></ChartSeriesStack>
                                    </ChartSeries>

                                    <ChartSeries Type="ChartSeriesType.Bar" Name="Product 2" Data="@series2Data">
                                        <ChartSeriesStack Group="myStack"></ChartSeriesStack>
                                    </ChartSeries>

                                </ChartSeriesItems>

                                <ChartCategoryAxes>
                                    <ChartCategoryAxis>
                                        <ChartCategoryAxisMajorGridLines Visible="false" />
                                    </ChartCategoryAxis>
                                </ChartCategoryAxes>

                              <ChartValueAxes>
                                    <ChartValueAxis>
                                        <ChartValueAxes>
                                            <ChartValueAxis Visible="false" />
                                        </ChartValueAxes>
                                    </ChartValueAxis>
                                </ChartValueAxes>
                           

                                <ChartLegend Visible="false">
                                </ChartLegend>



                            </TelerikChart>

I have tried hiding major and minor gridlines,  in the Y, X, and value Axis to no avail. 

I would be so grateful if someone could point me in the right direction.

 

Thank you 

Becca

 

Svetoslav Dimitrov
Telerik team
 answered on 12 May 2021
0 answers
272 views
I've noticed a strange bechavior of the grid filtering when pageable is true. When grid initialized, we show records by 10 per page, paging works fine,  filtering as well. But, if grid is filtered by some value and we press the button to clear a filtering value, pageable doesn't work, grid loads all data at once. There are a lot of rows and grid freezes a few seconds. How can we fix it, so after clear filters value, grid show data by page?

Evgeny
Top achievements
Rank 1
 asked on 11 May 2021
1 answer
123 views

Hi everybody,

I'm using the InCell EditMode for a TreeList. In my TreeList are present some columns where I don't want to permit the user to edit the value, so from start I'm using the OnEditEventHandler which has as arguments the ItemCommandEventArgs setting the IsCancelled property to true.

But If I want to filter out the column on which I want to allow the user to edit the value using the Field property it says that the Field Property is depricated. 

So is there another way to solve this issue?

Thank you.

Marin Bratanov
Telerik team
 answered on 11 May 2021
1 answer
278 views

I have a Right Drawer containing a nested Left Drawer. In the OnInitializedAsync, i have a loop doing nothing: this loop increases my RAM usage until my application crashes with "Out of memory", like there was a memory leak.

If i remove the nested Left Drawer, memory usage doesn't increase anymore.

I've made the loop part just to simulate the "Out of memory" we get in the real application, when we have to handle a lot of SignalR events.

<TelerikDrawer @ref="RightDrawer" Class="right-drawer" Data="RightMenuItems" Mode="DrawerMode.Overlay" Position="DrawerPosition.Right" @bind-Expanded="IsRightMenuExpanded"> <Template> <div class="k-drawer-items"> <ul> @foreach (var item in RightMenuItems) { <li @onclick:stopPropagation @onclick="(() => RightMenuItemClick(item))" class="k-drawer-item @GetSelectedRightMenuItemCssClass(item)" style="height: 40px; vertical-align: middle; padding-top: 0; padding-bottom: 0; white-space: nowrap"> <div> <span class="@item.IconClass" style="vertical-align:middle;"></span> <span class="k-item-text" style="vertical-align:middle;">@item.Text</span> @if (RightDrawer.Expanded && item.Expanded && (item.Children?.Any() ?? false)) { <span class="k-icon k-i-arrow-chevron-down" style="position:absolute; right:0; line-height:inherit; margin:0 8px; vertical-align:middle;"></span> } else if (RightDrawer.Expanded && !item.Expanded && (item.Children?.Any() ?? false)) { <span class="k-icon k-i-arrow-chevron-right" style="position:absolute; right:0; line-height:inherit; margin:0 8px; vertical-align:middle;"></span> } </div> </li> } </ul> </div> </Template> <Content> <!-- The nested drawer is the Push drawer - the CSS rule above reduces its z-index so it does not show up above the overlay of the other --> <TelerikDrawer Class="left-drawer" Data="LeftMenuItems" Mode="DrawerMode.Push"> <Content> <div id="main-layout-content"> @Body </div> </Content> </TelerikDrawer> </Content> </TelerikDrawer>


This is the OnInitializedAsync:


protected override async Task OnInitializedAsync()
        {
            StateHasChanged();

            Text = "Start";
            
            await Task.Delay(1000);

            for (int i = 0; i < 10000000; i++)
            {
                await Task.Delay(1);
            }
            await Task.Delay(1000);
            Text = "End";

        }

Marin Bratanov
Telerik team
 answered on 10 May 2021
1 answer
1.4K+ views
Is there a way to load a razor page into the WindowContent section of the Blazor Window? Similar to how this works with RadWindow in Telerik Ajax. Basically the goal is to have a universal Telerik window that we can pass parameters and launch from any page. When the Window launches it would load the relevant content page (passed from one of the parameters). For instance a site privacy document within the window.
Marin Bratanov
Telerik team
 answered on 10 May 2021
1 answer
1.3K+ views

I have my solution as an API Server on .Net 5 that does all the weightlifting, Elsa workflows, database IO & integrations. The portal is a Blazor Server-Side application on .Net 5. The deployment is like so:

 

The portal connects with the API with the standard HttpClient dependency injection. Here is the API setup first:

API - Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                using IHost host = CreateHostBuilder(args).Build();
                host.Run();
            }
            catch (Exception ex)
            {
                if (Log.Logger == null || Log.Logger.GetType().Name == "SilentLogger")
                {
                    Log.Logger = new LoggerConfiguration()
                        .MinimumLevel.Debug()
                        .WriteTo.Console()
                        .CreateLogger();
                }

                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        private static IHostBuilder CreateHostBuilder(string[] args)
           => Host.CreateDefaultBuilder(args)
                  .UseServiceProviderFactory(new AutofacServiceProviderFactory(Register))
                  .ConfigureWebHostDefaults(webBuilder =>
                  {
                    webBuilder.UseStartup<Startup>()
                       .CaptureStartupErrors(true)
                       .ConfigureAppConfiguration(config => { config.AddJsonFile("appSettings.Local.json", optional: true); })
                       .UseSerilog((hostingContext, loggerConfiguration) =>
                       {
                           loggerConfiguration
                               .ReadFrom.Configuration(hostingContext.Configuration)
                               .Enrich.FromLogContext()
                               .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name)
                               .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment);

                            #if DEBUG
                           loggerConfiguration.Enrich.WithProperty("DebuggerAttached", Debugger.IsAttached);
                            #endif
                       });
                  });

        private static void Register(ContainerBuilder builder) => builder.RegisterLogger(autowireProperties: true);

    }


API - Startup.cs

    public class Startup
    {
        private IWebHostEnvironment CurrentEnvironment { get; }
        private IConfiguration      Configuration      { get; }

        private const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration      = configuration;
            CurrentEnvironment = env;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();

            services.AddControllers()
                    .AddJsonOptions(options =>
                     {
                         options.JsonSerializerOptions.IgnoreNullValues = true;
                         options.JsonSerializerOptions.WriteIndented    = true;
                     });

            services.AddMvc(options => options.EnableEndpointRouting = false)
                    .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                    .AddXmlSerializerFormatters();

            services.AddHealthChecks();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title   = "Api",
                    Version = "v1",
                    Contact = new OpenApiContact
                    {
                        Name  = "Me",
                        Email = "Me@Company.co",
                        Url   = new Uri("https://internet exposed url/")
                    }
                });
            });

            services.AddDbContext<PrimaryDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("PrimaryConnection")));

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                    .AddJwtBearer(options =>
                     {
                         options.TokenValidationParameters = new TokenValidationParameters
                         {
                             ValidateIssuer           = true,
                             ValidateAudience         = true,
                             ValidateLifetime         = true,
                             ValidateIssuerSigningKey = true,
                             ValidIssuer              = Configuration["Tokens:Issuer"],
                             ValidAudience            = Configuration["Tokens:Issuer"],
                             IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                             ClockSkew                = TimeSpan.Zero,
                         };
                     });

            services.AddCors(options => {
                options.AddPolicy(MyAllowSpecificOrigins,
                                  builder => {
                                      builder.AllowAnyOrigin();
                                  });
            });

            services.AddMediatR(typeof(Startup));
            services.RegisterAutoMapper();

            services.Configure<SmtpSettings>(Configuration.GetSection("SmtpSettings"));
            services.AddSingleton<IMailer, Mailer>();
            services.AddSingleton<ISmtpServiceCustom, SmtpServiceCustom>();

            RegisterServices(services);
            ConfigureWorkflowService(services);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseSwagger();

            if (CurrentEnvironment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "Staging Api v1"); });
            }
            else
            {
                app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/swagger.json", "Production Api v1"); });
            }

            app.UseSerilogRequestLogging();

            app.UseStaticFiles();
            app.UseHttpActivities();
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseCors(MyAllowSpecificOrigins);
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseHealthChecks("/health", new HealthCheckOptions { ResponseWriter = JsonResponseWriter });
            app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
        }

        private static void RegisterServices(IServiceCollection services) => DependencyContainer.RegisterServices(services);

        private void ConfigureWorkflowService(IServiceCollection services)
        {
            // Elsa setup
        }

        private static Task JsonResponseWriter(HttpContext context, HealthReport report)
        {
            context.Response.ContentType = "application/json";
            return JsonSerializer.SerializeAsync(context.Response.Body, new { Status = report.Status.ToString() }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
        }

    }

 

API Controller

    [ApiController]
    [Route("api/[controller]")]
    [EnableCors("_myAllowSpecificOrigins")]
    public class AttachmentController : ControllerBase
    {
        private readonly ILogger<AttachmentController> _logger;
        private readonly IBudgetReleaseRequestService  _mainService;

        private readonly string _uploadFolderPath;

        public AttachmentController(IWebHostEnvironment hostingEnvironment, ILogger<AttachmentController> logger, IBudgetReleaseRequestService mainService)
        {
            _logger             = logger;
            _mainService        = mainService;
            _uploadFolderPath   = Path.Combine(hostingEnvironment.WebRootPath, "uploads");

            if (!Directory.Exists(_uploadFolderPath)) Directory.CreateDirectory(_uploadFolderPath);
        }

        [HttpPost]
        [Route("UploadFileTelerik")]
        public async Task<IActionResult> UploadFileTelerik(IFormFile brrAttachment)
        {
            if (brrAttachment == null) return new EmptyResult();

            try
            {
                var fileContent  = ContentDispositionHeaderValue.Parse(brrAttachment.ContentDisposition);

                if (fileContent.FileName != null)
                {
                    var fileName     = Path.GetFileName(fileContent.FileName.Trim('"'));
                    var physicalPath = Path.Combine(_uploadFolderPath, fileName);

                    await using var fileStream = new FileStream(physicalPath, FileMode.Create);
                    await brrAttachment.CopyToAsync(fileStream);
                }
            }
            catch
            {
                // Implement error handling here, this example merely indicates an upload failure.
                Response.StatusCode = 500;
                await Response.WriteAsync("some error message"); // custom error message
            }

            // Return an empty string message in this case
            return new EmptyResult();
        }

        [HttpPost]
        public ActionResult Remove(string fileToRemove)
        {
            if (fileToRemove == null) return new EmptyResult();

            try
            {
                var fileName     = Path.GetFileName(fileToRemove);
                var physicalPath = Path.Combine(_uploadFolderPath, fileName);

                if (System.IO.File.Exists(physicalPath))
                {
                    System.IO.File.Delete(physicalPath);
                }
            }
            catch
            {
                Response.StatusCode = 500;
                Response.WriteAsync("some error message");
            }

            return new EmptyResult();
        }

        #region Private

        private static string GetMimeTypeFromExtension(string fileDtoFileExtension)
        {
            return fileDtoFileExtension switch
            {
                ".txt"  => "text/plain",
                ".png"  => "image/png",
                ".jpeg" => "image/jpeg",
                ".jpg"  => "image/jpeg",
                ".doc"  => "application/vnd.ms-word",
                ".docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                ".xls"  => "application/vnd.ms-excel",
                ".xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                ".ppt"  => "application/vnd.ms-powerpoint",
                ".pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
                ".pdf"  => "application/pdf",
                _       => "application/octet-stream"
            };
        }       

        #endregion

    }


Portal - Program.cs

    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                using IHost host = CreateHostBuilder(args).Build();
                host.Run();
            }
            catch (Exception ex)
            {
                if (Log.Logger == null || Log.Logger.GetType().Name == "SilentLogger")
                {
                    Log.Logger = new LoggerConfiguration()
                        .MinimumLevel.Debug()
                        .WriteTo.Console()
                        .CreateLogger();
                }

                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
            => Host.CreateDefaultBuilder(args)
                   .UseServiceProviderFactory(new AutofacServiceProviderFactory(Register))
                   .ConfigureWebHostDefaults(webBuilder =>
                   {
                       webBuilder.UseStartup<Startup>()
                        .CaptureStartupErrors(true)
                        .ConfigureAppConfiguration(config => { config.AddJsonFile("appsettings.Local.json", optional: true); })
                        .UseSerilog((hostingContext, loggerConfiguration) => {
                            loggerConfiguration
                                .ReadFrom.Configuration(hostingContext.Configuration)
                                .Enrich.FromLogContext()
                                .Enrich.WithProperty("ApplicationName", typeof(Program).Assembly.GetName().Name)
                                .Enrich.WithProperty("Environment", hostingContext.HostingEnvironment);

                            #if DEBUG
                            loggerConfiguration.Enrich.WithProperty("DebuggerAttached", Debugger.IsAttached);
                            #endif
                        });
                   });

        private static void Register(ContainerBuilder builder) => builder.RegisterLogger(autowireProperties: true);

    }


Portal - Startup.cs

    public class Startup
    {
        private IWebHostEnvironment CurrentEnvironment { get; }
        private IConfiguration      Configuration      { get; }

        public Startup(IConfiguration configuration, IWebHostEnvironment env)
        {
            Configuration      = configuration;
            CurrentEnvironment = env;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();
            services.AddRazorPages();

            services.AddResponseCompression(options => {
                options.EnableForHttps = true;
                options.MimeTypes = new[] {
                    "text/plain",
                    "text/css",
                    "application/javascript",
                    "text/html",
                    "application/xml",
                    "text/xml",
                    "application/json",
                    "text/json"
                };
            });

            if (CurrentEnvironment.IsDevelopment() || Configuration["DeveloperHacks:ExtraException"] == "1")
            {
                services.AddServerSideBlazor(o => o.DetailedErrors = true);
            }
            else
            {
                services.AddServerSideBlazor(o => o.DetailedErrors = true)
                    .AddHubOptions(options =>
                    {
                        options.ClientTimeoutInterval = TimeSpan.FromMinutes(10);
                        options.KeepAliveInterval = TimeSpan.FromSeconds(3);
                        options.HandshakeTimeout = TimeSpan.FromMinutes(10);
                    });
            }

            services.AddHeadElementHelper();
            services.AddBlazorDragDrop();
            services.AddDevExpressBlazor();
            services.AddTelerikBlazor();

            services.AddAuthentication(sharedOptions =>
                     {
                         sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                         sharedOptions.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                         sharedOptions.DefaultSignOutScheme      = CookieAuthenticationDefaults.AuthenticationScheme;
                         sharedOptions.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
                     })
                    .AddOpenIdConnect(options =>
                     {
                         options.ClientId                                 = Configuration["Okta:ClientId"];
                         options.ClientSecret                             = Configuration["Okta:ClientSecret"];
                         options.Authority                                = Configuration["Okta:Issuer"];
                         options.CallbackPath                             = "/authorization-code/callback";
                         options.ResponseType                             = "code";
                         options.SaveTokens                               = true;
                         options.UseTokenLifetime                         = false;
                         options.GetClaimsFromUserInfoEndpoint            = true;
                         options.TokenValidationParameters.ValidateIssuer = false;
                         options.TokenValidationParameters.NameClaimType  = "name";
                         options.Scope.Add("openid");
                         options.Scope.Add("profile");
                     })
                    .AddCookie();

            services.AddMediatR(typeof(Startup));

            RegisterServices(services);
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseSerilogRequestLogging();

            app.UseHeadElementServerPrerendering();

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }

        private void RegisterServices(IServiceCollection services)
        {
            var baseAddress = Configuration["ApiSetup:BaseAddress"]; // value: http://localhost:8082/

            services.AddHttpClient<ILookupService,           LookupService>          (client => { client.BaseAddress = new Uri(baseAddress); });
            services.AddHttpClient<IBusinessLookupService,   BusinessLookupService>  (client => { client.BaseAddress = new Uri(baseAddress); });
            services.AddHttpClient<IApiUserService,          ApiUserService>         (client => { client.BaseAddress = new Uri(baseAddress); });
            services.AddHttpClient<IRequestService,          RequestService>         (client => { client.BaseAddress = new Uri(baseAddress); });
            services.AddHttpClient<IResourceService,         ResourceService>        (client => { client.BaseAddress = new Uri(baseAddress); });
            services.AddHttpClient<IApproverTemplateService, ApproverTemplateService>(client => { client.BaseAddress = new Uri(baseAddress); });
            services.AddHttpClient<IAttachmentService,       AttachmentService>      (client => { client.BaseAddress = new Uri(baseAddress); });
        }

    }

Razor Page:

@page "/request-handle"
@page "/authorization-code/request-handle"

@page "/request-handle/{requestId:long}"
@page "/authorization-code/request-handle/{requestId:long}"

@page "/request-handle/{requestId:long}/{actorId}"
@page "/authorization-code/request-handle/{requestId:long}/{actorId}"

@page "/request-handle/{requestId:long}/{actionId:guid}"
@page "/authorization-code/request-handle/{requestId:long}/{actionId:guid}"

@inherits RequestHandleModel

@attribute [Authorize]

<PageHeader PageTitle="Release Request" AreaName="Request"></PageHeader>

@if (Model != null)
{
    <EditForm Context="_" OnValidSubmit="@HandleValidSubmit" EditContext="@EditContextCustom">
        <DataAnnotationsValidator />

        <DxFormLayout CssClass="dxFormLayoutHeaderStyle" CaptionPosition="CaptionPosition.Vertical">
            <DxFormLayoutItem ColSpanMd="12">
                <Template>
                    <ValidationSummary />
                </Template>
            </DxFormLayoutItem>

            <DxFormLayoutGroup Caption="Files" ColSpanMd="12">
                <DxFormLayoutItem Caption="" ColSpanMd="12" >
                    <Template >
                        <TelerikUpload SaveUrl="@FileUploaderUrlT"
                                       SaveField="brrAttachment" RemoveField="fileToRemove"
                                       AllowedExtensions="@(new List<string> {".jpg", ".jpeg", ".png", ".pdf", ".xlsx", ".xls", ".doc", ".docx"})"
                                       MaxFileSize="26214400" MinFileSize="1024">
                        </TelerikUpload>
                    </Template >
                </DxFormLayoutItem >
            </DxFormLayoutGroup>            
        </DxFormLayout>
    </EditForm>
}
else
{
    <p>@LoadingMessage</p>
}

<TelerikLoaderContainer Size="LoaderSize.Large" OverlayThemeColor="dark" LoaderPosition="LoaderPosition.Top" Text="Please wait..." LoaderType="LoaderType.ConvergingSpinner" Visible="@LoaderContainerVisible" />

<TelerikNotification Class="high-zindex" @ref="@Notification" AnimationType="AnimationType.Fade" AnimationDuration="300" />

Razor CodeBehind:


protected string FileUploaderUrlT = $"{ConfigHelper["ApiSetup:BaseAddress"]}api/Attachment/UploadFileTelerik";

// where ApiSetup:BaseAddress => 
// http://localhost:8082/

 

Through the portal, the registered clients work perfectly. However, the Upload Control fails at uploading a file:

Details: Preflight

Details: XHR

The request URL is perfectly correct. The API server is never hit. This setup works fine on my dev machines. It fails only when on staging or production. I cannot expose the API in any other way. I am looking at these two topics as I'm searching:

Upload component reports 'File failed to upload' 

File Upload fails with error 404 in API call

Any hep will be appreciated.

Marin Bratanov
Telerik team
 answered on 08 May 2021
0 answers
252 views

I have a Blazor grid and when I click the column heading it sorts the data Ascending.  If I click the same column heading again, I'm expecting it to toggle to Descending, but the DataSourceRequest object always has Ascending regardless.

I see that the Telerik Demos work and I don't think I've done much different that those.  I notice in the demos there is an arrow indicating which way the sort is going, in my grid no arrow icon is visible.

 

Adrian
Top achievements
Rank 1
Iron
Veteran
Iron
 asked on 07 May 2021
1 answer
343 views

Hi,

I have inherited a data access layer which uses OrmLite and the database POCOs have been auto generated and it uses the actual database column names as the property names in the POCOs.

e.g. person_firstname, person_lastname etc.

public class PersonPoco
{
    public string person_firstname { get; set; }
    public string person_lastname { get; set; }
}

Then I'm using AutoMapper to map the POCOs to business objects which in turn are used as the data source for the Telerik Grid.

public class PersonBusinessClass
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

So in the Telerik Grid I would bind the columns as so:

<GridColumn Field="@(nameof(PersonBusinessClass.Firstname))" Title="First Name" />
<GridColumn Field="@(nameof(PersonBusinessClass.Lastname))" Title="Last Name" />

This causes an issue because when it comes to column filtering/sorting it uses the GridColumn Field value for the database column name which in my case is different, so I end up with errors e.g: 

Invalid column name 'Firstname' as it should be 'person_firstname'.
Invalid column name 'Lastname' as it should be 'person_lastname'.

Is there a way to specify a different column name to use for filtering/sorting ?

Marin Bratanov
Telerik team
 answered on 07 May 2021
2 answers
1.3K+ views

I have a Telerik Blazor Grid that I want to be able to use built in column filtering, column sort and paging.

There is a large amount of data to be displayed in the grid approx. 200,000+ rows hence the need for paging.

Ideally I want to do all the filtering, sorting and paging within the SQL query so that the SQL server will do the heavy lifting and only send back the required single page of data based on the applied filters, sorting and page number.

I have the Telerik.DataSource.DataSourceRequest object from the grid that contains all the grid state for currently applied filters, sorting and page number, is there a way I can use this object to generate my SQL query e.g. create the WHERE clause based on the filters and the ORDER BY clause based on the sorting and the page of data based on the page number?

I am using ServiceStack OrmLite which is returning an IQueryable from the SQL database then I'm using the extension method .ToDataSourceResultAsync(gridRequest);

I seems that the grid state in the gridRequest is happening in memory on the data sent back from the SQL query in the IQueryable object and not on the SQL database.

Is there a way I can do the filtering etc on the SQL database within the query rather than in memory?

Example:

            DataSourceResult processedData = null;

            using (var db = _dbConnectionFactory.Open())
            {
                Telerik.DataSource.DataSourceRequest gridRequest = dataSourceRequestWrapper.ToDataSourceRequest();

                var q = db.From<PersonTable>().Limit(0, 100);

                processedData = await db.Select(q).AsQueryable().ToDataSourceResultAsync(gridRequest);

                db.Close();
            }

            return processedData;

This produces a SQL query like:

SELECT
        TOP 100
        "PersonId", 
        "FirstName", 
        "Surname", 
        "Age" 
FROM
        "dbo"."PersonTable"

Ideally with using the extension method .ToDataSourceResultAsync(gridRequest); I would like to see the SQL query look more like based on the grid being sorted by the Age column descending and a single text filter applied to the Surname column to filter on 'Smith':

SELECT
        TOP 100
        "PersonId", 
        "FirstName", 
        "Surname", 
        "Age" 
FROM
        "dbo"."PersonTable"
WHERE
        "Surname" LIKE 'Smith%'
ORDER BY
        "Age" DESC



Adrian
Top achievements
Rank 1
Iron
Veteran
Iron
 updated answer on 07 May 2021
Top users last month
Will
Top achievements
Rank 2
Iron
Motti
Top achievements
Rank 1
Iron
Hester
Top achievements
Rank 1
Iron
Bob
Top achievements
Rank 3
Iron
Iron
Veteran
Thomas
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?