Telerik Forums
UI for Blazor Forum
1 answer
2 views

Hy,

I created a generic class for telerik grids to manage different data models.

In this class I use OnRead event for reading data :

 protected async Task OnReadHandlerAsync(GridReadEventArgs args)
 {
     try
     {
         var query = Service.QueryDto();
         query = DefaultFilterCondition is not null ? query.Where(DefaultFilterCondition) : query;
         var dataSourceResult = await query.ToDataSourceResultAsync(args.Request);
         if (args.Request.Aggregates.Any())
         {
             args.AggregateResults = dataSourceResult.AggregateResults;
         }
         args.Data = dataSourceResult.Data;
         args.Total = dataSourceResult.Total;
     }
     catch (Exception ex)
     {
         NotificationService.Error(ex.Message);
     }
 }

As you can see I use the ToDataSourceResult extension on a variable of type IQueryable<TDto> for automatic sorting, filtering,paging,...

But now I have a problem: I created a grid that contains aggregates, now for this TelerikGrid the application throws the "must be reducible node exception" when the "ToDataSourceResult" is executed on the IQueyable<TDto> variable. 

My TelerikGrid with aggregates:

@inherits GridReadOnlyComponentBase<SimulationResultService,SimulationResultDto>
<TelerikGrid Id="simulationresultgrid"
             @ref="GridRef"
             TItem="SimulationResultDto"             
             OnStateInit="@OnStateInitHandler"
             FilterMode="@GridFilterMode.FilterRow"
             EditMode="@GridEditMode.None"
             SelectionMode="@GridSelectionMode.None"             
             Sortable="@true" SortMode="@SortMode.Single"
             Groupable="@true" LoadGroupsOnDemand="@false"
             Reorderable="@false"                                                                 
             OnRead="@OnReadHandlerAsync">

     <GridAggregates>
        <GridAggregate Field="@nameof(SimulationResultDto.ActualSales)" Aggregate="@GridAggregateType.Sum" FieldType="typeof(decimal)" />
        <GridAggregate Field="@nameof(SimulationResultDto.YearImpact)" Aggregate="@GridAggregateType.Sum" FieldType="typeof(decimal)" />
        <GridAggregate Field="@nameof(SimulationResultDto.ChangesImpact)" Aggregate="@GridAggregateType.Sum" FieldType="typeof(decimal)" />
    </GridAggregates> 

    <NoDataTemplate>
        <strong>@(_simulationId > 0 ? "Nessun dato presente,eseguire prima una simulazione" : "Scegli la simulazione")</strong>
    </NoDataTemplate>

    <GridToolBarTemplate>
        <span class="k-toolbar-spacer" />
        <SimulationSelect SelectedValue="_simulationId" SelectedValueChanged="SimulationIdChanged" Width="30%" />
    </GridToolBarTemplate>

    <GridColumns>        
        <GridColumn Field="@nameof(SimulationResultDto.ActualSales)"
                    Title="Fat. attuale"
                    Width="200px" DisplayFormat="{0:C}"
                    Filterable="false"
                    Groupable="false">
             <GroupFooterTemplate>
                TOT: <TelerikNumericTextBox Width="80%" ReadOnly="@true" Arrows="@false" Decimals="2" Format="C" @bind-Value="@context.Sum" />
            </GroupFooterTemplate> 
        </GridColumn>        
    </GridColumns>

I know that a solution could be to run the ToList before running the ToDataSourceResult but I would like to know if there is another solution as I work with a large amount of data.

Thanks

Svetoslav Dimitrov
Telerik team
 answered on 28 Mar 2024
0 answers
1 view

I have a basic .net8 project , the VS template one, I following the instructions to hook up telerik to it.

The btn works.

I then added a grid, which shows up, but I see no records in it. I dont see what I am doing wrong.

razor page:

@page "/GridTester"
<h3>GridTesting</h3>

<h1>@strTaskDone</h1>

<TelerikLoaderContainer Visible="@ldrVisible" Class="no-panel">
    <Template>
        <TelerikLoader></TelerikLoader>
        <div>
            <span></span>
            <span>Please wait, I am currenlty working on it...</span>
        </div>
    </Template>
</TelerikLoaderContainer>


<TelerikGridLayout>
    <GridLayoutColumns>
        <GridLayoutColumn Width="100%"></GridLayoutColumn>    
    </GridLayoutColumns>
    <GridLayoutRows>   
        <GridLayoutRow Height="@strAppMsgHT"></GridLayoutRow>               @*App Msg*@   
        <GridLayoutRow Height="@strGridHT"></GridLayoutRow>                 @*Report Grids *@
    </GridLayoutRows>
     <GridLayoutItems>
        <GridLayoutItem Row="1" Column="1" >
            <TelerikButton OnClick="@SayHelloHandler"
                           ThemeColor="@ThemeConstants.Button.ThemeColor.Primary">Say Hello</TelerikButton>
        </GridLayoutItem>
         <GridLayoutItem Row="2" Column="1" ColumnSpan="2">
            <TelerikGrid @ref="@gridOrderListDetails"
                         Data="@grdOrderListDetails"
                         AutoGenerateColumns="true"
                         Width="800px"
                         Pageable="true"
                         Sortable="true"
                         FilterMode="@GridFilterMode.FilterRow">
            </TelerikGrid>
        </GridLayoutItem>
    </GridLayoutItems>
</TelerikGridLayout>

code behind stuff for the Grid:

 public TelerikGrid<rtpOrderListDetailsResults> gridOrderListDetails { get; set; }  // grid on the webpage
 private List<rtpOrderListDetailsResults> grdOrderListDetails { get; set; }

 DataTable dt = new DataTable();
 SqlConnection con = new SqlConnection(strConn);
 SqlDataAdapter da = new SqlDataAdapter(strCMDToRun, con);
 da.SelectCommand.CommandTimeout = 540000;
 da.Fill(dt);
 foreach (DataRow row in dt.Rows)
 {
     if (dt.Columns.Count == 1)
     {
         ResultRow = new rtpOrderListDetailsResults();
         ResultRow.PON = row["Result"] as string;
     }
     else
     {
         ResultRow = new rtpOrderListDetailsResults();
         ResultRow.PON = row["PON"] as string;
         ResultRow.Customer_ID = (Int64)row["Customer_ID"];
         ResultRow.Customer_Name_Billing = row["Customer_Name_Billing"] as string;
         ResultRow.Parent_Name = row["Parent_Name"] as string;
         ResultRow.TN = row["TN"] as string;
         ResultRow.Nbr_Of_Actual_Lines = (Int32)row["Nbr_Of_Actual_Lines"];

         if (row["CreatedDT"] != DBNull.Value)
         {
             d = DateOnly.FromDateTime((DateTime)row["CreatedDT"]);
             ResultRow.CreatedDT = d;
         };

         if (row["DueDT"] != DBNull.Value)
         {
             d = DateOnly.FromDateTime((DateTime)row["DueDT"]);
             ResultRow.DueDT = d;
         };

         ResultRow.Current_Status = row["Current_Status"] as string;

         if (row["Current_StatusDT"] != DBNull.Value)
         {
             d = DateOnly.FromDateTime((DateTime)row["Current_StatusDT"]);
             ResultRow.Current_StatusDT = d;
         };
         // ResultRow.Current_StatusDT = row["Current_StatusDT"] as DateTime?;

         ResultRow.Provisioner_Assigned = row["Provisioner_Assigned"] as string;
         ResultRow.Agent_Is = row["Agent_Is"] as string;
         ResultRow.Carrier = row["Carrier"] as string;
         ResultRow.Carrier_ID = (Int32)row["Carrier_ID"];
         ResultRow.Provisioning_Process = row["Provisioning_Process"] as string;
         ResultRow.Class = row["Class"] as string;
         ResultRow.Provisioning_Age_Days = (Int32)row["Provisioning_Age_Days"];
         ResultRow.Order_Type = row["Order_Type"] as string;
         ResultRow.Line_Type = row["Line_Type"] as string;
         ResultRow.Line_Description = row["Line_Description"] as string;
         ResultRow.State = row["State"] as string;
         ResultRow.Open_Related_Orders = row["Open_Related_Orders"] as string;
         ResultRow.Channel = row["Channel"] as string;
         ResultRow.Bill_Profile = row["Bill_Profile"] as string;

         ResultRow.MRC_ChargesAmt = (decimal)row["MRC_ChargesAmt"];
         ResultRow.MRC_Line_ChargesAmt = (decimal)row["MRC_Line_ChargesAmt"];

         ResultRow.Cancel_Reason = row["Cancel_Reason"] as string;
         ResultRow.Hold_Reason = row["Hold_Reason"] as string;
         ResultRow.Prime = row["Prime"] as string;
         ResultRow.Cycle_Is = (Int32)row["Cycle_Is"];
         // ResultRow.Impacted_By_COVID19 = row["Impacted_By_COVID19"] as string;
         ResultRow.Term_Nber_Of_Months = (Int32)row["Term_Nber_Of_Months"];
         ResultRow.Upload = row["Upload"] as string;
         ResultRow.Download = row["Download"] as string;
         ResultRow.AMProjectManager = row["AMProjectManager"] as string;

         RptResults.Add(ResultRow);
     };


 };

 grdOrderListDetails = RptResults;

 if (gridOrderListDetails.Data.Count() > 0)
 {
     gridOrderListDetails.AutoFitAllColumns();
 };

 if (grdOrderListDetails.Count > 0)
 {
     strTaskDone = "Completed";
 }
 else
 {
     strTaskDone = "Me Sad";
 };

This has data: grdOrderListDetails.Count

But this is NULL: gridOrderListDetails.Data

Why? 

 

Deasun
Top achievements
Rank 3
Bronze
Bronze
Bronze
 asked on 27 Mar 2024
1 answer
8 views
I have a form with an edit button and a grid. The EditMode property of the grid is set to a reference variable named @GridEditModeValue which has an initial value on page load of GridEditMode.None. When I press the Edit button of the Form, in the OnClick handler I set @GridEditModeValue=GridEditMode.Incell. This allows me to click into the cells of the grid and make changes to their values, however when i click out of the cell to another part of the form or to click the Submit button of the form, the OnUpdate event doesn't seem to fire and the changes are lost. If I click into a different cell of the grid, the event does fire and the event handler is executed correctly. Is there any way to have this event fire when the cell loses focus in this case?
Dimo
Telerik team
 answered on 21 Mar 2024
1 answer
8 views
My project's Theme Builder is set up to show an alternating color for the TelerikGrid rows.  However, if I use a compact grid through Grid Sizing by setting Size="@ThemeConstants.Grid.Size.Small", the alternating row color disappears.  How can I get the alternating rows when using the Small Grid Theme?
Dimo
Telerik team
 answered on 21 Mar 2024
1 answer
15 views

Hello I have a grid which has a "Add" button which is defined in a GridBarToolBarTemplate which opens a pop up used for adding a new record displaying in the Grid.

With Blazor .Net 8 I am using Stream rendering to show the grid.

I now want to put the add button in a different component so I can use another "Interactive" rendering mode just for adding a new record

I have tried during this but it doesnt seem to work. Is this possible? and how do Iget it to work?

Thanks

Aj

 

 

Dimo
Telerik team
 answered on 21 Mar 2024
4 answers
6.0K+ views

How do I right-align grid column values? I tried the Template with a span but it does not seem to work and it also adds another element.

 

This does not work:

                <GridColumn Field="Amount">
                    <Template>
                        <span style="text-align:right">
                            @((context as BO).Amount.ToString("C"))
                        </span>
                    </Template>
                </GridColumn>

 

Thanks.

 

Joel

 

Leland
Top achievements
Rank 1
Iron
Iron
 updated answer on 19 Mar 2024
0 answers
8 views

I implemented the AutoFitAllColumnsAsync() on the CustomGrid, but the column don't resize

Please see structure below

<CustomGrid @ref="@Grid"

OnRead="@OnGridRead" TItem="@Product" Pageable="true" Sortable="true" Resizable="true" FilterMode="GridFilterMode.FilterRow"> <GridColumns>

<CascadingValue Value="grid.GetDistinctColumnFilterValues">

<CustomGridColumn Field="@nameof(Product.Name)" Title="Product Name" /> <CustomGridColumn Field="@nameof(Product.Price)" /> <CustomGridColumn Field="@nameof(Product.ReleaseDate)" Title="Release Date" /> <CustomGridColumn Field="@nameof(Product.Active)" />

<CascadingValue>

</GridColumns>

</CustomGrid>

Glendys
Top achievements
Rank 1
 asked on 19 Mar 2024
2 answers
17 views

The exception is only raised when applying a filter , sorting up and down works ok. Using "contains" filter.

If I remember correctly, this worked before and I did not change my code AFAIK.

Controller side looks like this:

        [HttpPost]
        [SwaggerResponse(StatusCodes.Status200OK)]
        [SwaggerResponse(StatusCodes.Status404NotFound)]
        [Route(ApiUrlConstants.DataSourceRequestSubUrl)]
        public IActionResult DataSourceRequest(string projectIdentifier, [FromBody] DataSourceRequest request)
        {
            if (!TryGetProject(projectIdentifier, out var project))
                return this.NotFoundResult(nameof(projectIdentifier), projectIdentifier);
            var collection = GetCollection(project).Select(MapItemTypeToDto);
            var resultData = collection.ToDataSourceResult(request);
            return Ok(resultData);
        }


WebUI/Client side OnRead event looks like this (the request is sent to server without any further changes):

        private async Task ReadItems(GridReadEventArgs args)
        {
            var dataSourceResult = CollectionClient?.HasValidPath ?? false
                ? await CollectionClient.DataSourceRequestAsync(args.Request)
                : new();
            args.Data = dataSourceResult?.Data;
            args.Total = dataSourceResult?.Total ?? 0;
        }

which raises an exception in my API server , log looking like this:


fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.ArgumentException: Provided expression should have string type (Parameter 'stringExpression')
         at Telerik.DataSource.Expressions.ExpressionFactory.LiftStringExpressionToEmpty(Expression stringExpression)
         at Telerik.DataSource.Expressions.FilterOperatorExtensions.GenerateToLowerCall(Expression stringExpression, Boolean liftMemberAccess)
         at Telerik.DataSource.Expressions.FilterOperatorExtensions.GenerateCaseInsensitiveStringMethodCall(MethodInfo methodInfo, Expression left, Expression right, Boolean liftMemberAccess)
         at Telerik.DataSource.Expressions.FilterOperatorExtensions.GenerateContains(Expression left, Expression right, Boolean liftMemberAccess)
         at Telerik.DataSource.Expressions.FilterOperatorExtensions.CreateExpression(FilterOperator filterOperator, Expression left, Expression right, Boolean liftMemberAccess)
         at Telerik.DataSource.Expressions.FilterDescriptorExpressionBuilder.CreateBodyExpression()
         at Telerik.DataSource.FilterDescriptor.CreateFilterExpression(ParameterExpression parameterExpression)
         at Telerik.DataSource.FilterDescriptorBase.CreateFilterExpression(Expression instance)
         at Telerik.DataSource.Expressions.FilterDescriptorCollectionExpressionBuilder.CreateBodyExpression()
         at Telerik.DataSource.CompositeFilterDescriptor.CreateFilterExpression(ParameterExpression parameterExpression)
         at Telerik.DataSource.FilterDescriptorBase.CreateFilterExpression(Expression instance)
         at Telerik.DataSource.Expressions.FilterDescriptorCollectionExpressionBuilder.CreateBodyExpression()
         at Telerik.DataSource.Expressions.FilterExpressionBuilder.CreateFilterExpression()
         at Telerik.DataSource.Extensions.QueryableExtensions.Where(IQueryable source, IEnumerable`1 filterDescriptors)
         at Telerik.DataSource.Extensions.QueryableExtensions.CreateDataSourceResult[TModel,TResult](IQueryable queryable, DataSourceRequest request, Func`2 selector)
         at Telerik.DataSource.Extensions.QueryableExtensions.ToDataSourceResult(IQueryable queryable, DataSourceRequest request)
         at Telerik.DataSource.Extensions.QueryableExtensions.ToDataSourceResult(IEnumerable enumerable, DataSourceRequest request)
         at SNG.LccNion.API.Controllers.ProjectSubCollectionBaseController`2.DataSourceRequest(String projectIdentifier, DataSourceRequest request) in S:\Sources\LCCNion\Source\SNG.LccNion.API\Controllers\ProjectSubCollectionBaseController.cs:line 85
         at lambda_method21(Closure, Object, Object[])
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
         at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
         at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|7_0(Endpoint endpoint, Task requestTask, ILogger logger)
         at SNG.LccNion.API.JWTAuth.JwtMiddleware.Invoke(HttpContext context, IEnumerable`1 authenticationServices) in S:\Sources\LCCNion\Source\SNG.LccNion.API\StartupConfigs\JWTAuth\JWTMiddleware.cs:line 60
         at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Wich does not really help finding out was the problem is. Sorting on any column works ok. It just seems filtering is broken somehow.

Also tried other filter options: "Equals" (no results, no error, even though it should match something), "StartsWith" same error

Pretty sure I am doing something wrong, - but what? BTW I have the same trouble using a dropdownlistbox with an OnRead handlerevent.

Some version info:

  • Telerik.DataSource v3.0.1
  • Telerik.UI.for.Blazor 5.1.1
  • VS 2022, .NET8

TIA,

Hans

Hans
Top achievements
Rank 2
Iron
Iron
 answered on 19 Mar 2024
1 answer
25 views

I implemented the Localization on my project, and I got almost all of them. But the Column Menus and some drop downs aren't translating.

How can I achieve that?

Implementation

Program.cs

            // register a custom localizer for the Telerik components, after registering the Telerik services
            builder.Services.AddSingleton<ITelerikStringLocalizer, TelerikLocalizer>();
            builder.Services.AddLocalization();

TelerikLocalizer.cs

public class TelerikLocalizer : ITelerikStringLocalizer
{
    private readonly IStringLocalizer<Resources> globalLocalizer;

    public TelerikLocalizer(IStringLocalizer<Resources> globalLocalizer)
    {
        this.globalLocalizer = globalLocalizer;
    }

    public string this[string name] => GetStringFromResource(name);

    public string GetStringFromResource(string key)
    {
        var localString = Resources.ResourceManager.GetString(key, Resources.Culture);
        if (string.IsNullOrWhiteSpace(localString))
        {
            return globalLocalizer.GetString(key);
        }
        return localString;
    }
}

I have a list of about 19 languages

Source: https://github.com/telerik/blazor-ui/tree/master/common/localization

Hristian Stefanov
Telerik team
 answered on 19 Mar 2024
1 answer
29 views

Hi

Please could you share how you plan to support Blazor SSR mode? Do you intend to make as many components as possible SSR compatible? Do you envisage you will add interactivity to the components in SSR by using JavaScript?

Thanks

George

Dimo
Telerik team
 updated answer on 15 Mar 2024
Top users last month
horváth
Top achievements
Rank 2
Iron
Iron
Steve
Top achievements
Rank 2
Iron
Erkki
Top achievements
Rank 1
Iron
Mark
Top achievements
Rank 2
Iron
Iron
Veteran
Jakub
Top achievements
Rank 1
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?