Telerik Forums
UI for Blazor Forum
2 answers
113 views

I want the Grid to display correctly on different devices like Mobile And Tablet.

In other words, I want to have a Responsive Grid.

In such a way that the Grid is displayed correctly in different dimensions and the remaining columns that do not fit on the page are scrolled horizontally.
Please help me.
Currently, on different devices such as mobile and tablet, the Grid is displayed as small columns, which is not suitable at all.
Thanks

Mohamad Javad
Top achievements
Rank 2
Iron
Iron
Iron
 answered on 07 Jan 2025
1 answer
38 views

I have a TelerikGrid whose columns is dynamically populated with List<ExpandoObject>.
I need a TelerikProgressBar to display one of the columns. I have used the following code but TelerikProgressBar only displays the value of the first record for all rows and individual rows are not displayed properly in TelerikProgressBar.
Please help me.
Thanks

	
<GridColumns>
@{
	if (GridData != null && GridData.Any())
	{
		var firstDataItem = (IDictionary<string, object>)GridData.First();

		foreach (var item in firstDataItem)
		{
			if (item.Key != "ProgressBar_Num")
			{
				<GridColumn Field="@item.Key" FieldType="@item.Value.GetType()" @key="@item.Key">
					<Template>
						<TelerikProgressBar Class="width-100" Max="100" Value="(double)item.Value">
						</TelerikProgressBar>
					</Template>
											
				</GridColumn>
			}
		}
	}
}
</GridColumns>

Tsvetomir
Telerik team
 answered on 07 Jan 2025
1 answer
67 views

Is there a way to use a Switch control instead of checkbox in a TreeView? I am able to use ItemTemplate to insert a switch next to the checkbox but I need to replace the checkbox and have the switch use CheckChildren and CheckParents.

Any ideas?

Thanks!

<TelerikTreeView OnItemRender="@OnItemRender" CheckBoxMode="TreeViewCheckBoxMode.Multiple" CheckChildren="true" CheckParents="true" Data="@FlatData" @bind-ExpandedItems="@ExpandedItems">
    <TreeViewBindings>
        <TreeViewBinding TextField="Text" IdField="Id" ParentIdField="ParentId" ItemsField="Text" HasChildrenField="HasChildren" IconField="Icon">
            <ItemTemplate>
                @{var treeItem = (TreeItem)context; }
                <div class="treeview-item">
                    <TelerikSwitch @bind-Value="treeItem.IsChecked" />
                    <span>@treeItem.Text</span>
                </div>
            </ItemTemplate>
        </TreeViewBinding>
    </TreeViewBindings>
</TelerikTreeView>
Dimo
Telerik team
 answered on 02 Jan 2025
0 answers
37 views
TelerikEditor custom tool component: Paste any string, bold and italic not working. Could you please me suggest me how to resolve this issue?.
Shahil
Top achievements
Rank 1
 asked on 27 Dec 2024
1 answer
60 views

Couple of questions:

1.  When working Add command for a detail templated grid, the args parameter doesn't provide for the parent model so there is no way to quickly determine values needed from the parent that will populate the child/detail (like primary key values on a composite key).  I guess I can manually track "current parent row" via OnRowClick but that seems a bit tedious?  Surely there is an easier approach?  I was expecting the OnCreate for detail grid to provide parent object/model as part of the event parameters, but that doesn't seem to be the case.

2.  When working EditMode=InCell on a detail grid, my expectations was that when I click on an empty grid it would automatically put me into EditMode (Add) for a new detail row, but that doesn't seem to be the case?  I have to go thru the OnCreate (which doesn't provide for parent model).

I was reading thru your documentation here and here but they weren't useful for is a real world scenario as none of the examples show "Add" case on a detail item that relies on a parent key value to build a composite key when the data is actually saved to a database.

Any clean suggestions other than tracking "current parent row" via OnRowClick?

Rob.

Hristian Stefanov
Telerik team
 answered on 25 Dec 2024
1 answer
43 views
When enabling a GridSearchBox in my Grid, while I'm typing or deleting letters from the search box, I get spammed in my Ouput from Debug with

"Exception thrown: 'System.Threading.Tasks.TaskCanceledExceptuion' in System.Private.CoreLib.dll"

Here is my code:


<TelerikGrid Data=@TestItemsList
             FilterMode="GridFilterMode.FilterRow"
             Sortable="true"
             EditMode="GridEditMode.Inline"
             Height="2000px"
             FilterRowDebounceDelay="300">
    
    <GridToolBarTemplate>
        <GridCommandButton Command="Add" Icon="@SvgIcon.Plus" Enabled="@UserModel.CanEdit()">Add Item</GridCommandButton>
        <GridSearchBox Fields="@SearchableFields" Placeholder="Search..." Width="300px" />
    </GridToolBarTemplate>

    <GridColumns>
        <GridColumn Field="@nameof(TestModel.FileName)"
                    Title="File Name"
                    Editable="false" />

        <GridCommandColumn>
            <GridCommandButton Command="Save"
                               Icon="@SvgIcon.Save"
                               ShowInEdit="true"
                               Enabled="@UserModel.CanEdit()"
                               OnClick="@OnUpdate">
                Update
            </GridCommandButton>

            <GridCommandButton Command="Edit"
                               Icon="@SvgIcon.Pencil"
                               Enabled="@UserModel.CanEdit()">
                Edit
            </GridCommandButton>

            <GridCommandButton Command="Delete"
                               Icon="@SvgIcon.Trash"
                               Enabled="@UserModel.CanEdit()"
                               OnClick="@OnDelete">
                Delete
            </GridCommandButton>

            <GridCommandButton Command="Cancel"
                               Icon="@SvgIcon.Cancel"
                               ShowInEdit="true"
                               Enabled="@UserModel.CanEdit()">
                Cancel
            </GridCommandButton>

        </GridCommandColumn>

    </GridColumns>
</TelerikGrid>

@* Only showing relevent code here *@
@code {

    private List<string> SearchableFields = new List<string> { nameof(SDSModel.Title), nameof(SDSModel.FileName) };

}

Details:
System.Threading.Tasks.TaskCanceledException
  HResult=0x8013153B
  Message=A task was canceled.

Call Stack:
Tsvetomir
Telerik team
 answered on 24 Dec 2024
1 answer
108 views

Hi,

Is there any way to correctly display an HTML-formatted output using the TelerikAIPrompt control? The response I get from the API call is a Markdown string. I converted this to HTML, and all I see is text with the HTML tags printed (listed listed in the sample below). 

It would be nice to have a way to use (MarkupString) to ensure the HTML is correctly shown.

My code is listed below for reference:

@page "/aitest"

@inject Microsoft.Extensions.Options.IOptions<ServerConfig> ServerConfig;

@using Ganss.Xss;
@using Markdig;
@using Newtonsoft.Json.Linq;
@using RestSharp;

<TelerikAIPrompt OnPromptRequest="@HandlePromptRequest" @ref="@AIPromptRef">
</TelerikAIPrompt>

@code {
    private TelerikAIPrompt AIPromptRef { get; set; } = default!;

    private async Task HandlePromptRequest(AIPromptPromptRequestEventArgs args)
    {
        string url = "{url}";

        var options = new RestClientOptions(url);
        var client = new RestClient(options);
        var request = new RestRequest("", Method.Post);

        request.AddHeader("Content-Type", "application/json");
        request.AddJsonBody("{\"api_key\": \"" + ServerConfig.Value.APIKey.ToString() + "\", \"question\": \"" + args.Prompt + "\"}");

        RestResponse response = new();
        response = await client.PostAsync(request);

        JObject data = JObject.Parse(response.Content ?? string.Empty);

        var answer = data["answer"] switch
        {
            null => string.Empty,
            _ => data["answer"]!.ToString()
        };

        // Convert the Markdown in the output to HTML
        var pipeline = new MarkdownPipelineBuilder().UseAdvancedExtensions().Build();
        string html = Markdown.ToHtml(answer, pipeline);

        // Sanitize the HTML
        var sanitizer = new HtmlSanitizer();
        string safeHtml = sanitizer.Sanitize(html);

        args.Output = safeHtml;
    }
}
Hristian Stefanov
Telerik team
 answered on 24 Dec 2024
1 answer
74 views
I have a TelerikGrid utilizing the FilterRow for FilterMode. One of the columns is called CurrentVersion where the CurrentVersion could be a copy of multiple other objects but it's Revision is higher. The objects with CurrentVersion = true, I want to be the only initially displayed items. If there is an item that is CurrentVersion = false, I still want it to be accessible by changing the filter to All instead of True, but I need true to be the default. How would I go about this? I've checked documentation and can't find a solution. I've also checked online and other forums posts and can't seem to find a solution. ChatGPT and CoPilot are also no help here.

<TelerikGrid Data=@TestItemsList
             FilterMode="GridFilterMode.FilterRow"
             Sortable="true"
             EditMode="GridEditMode.Inline"
             Height="2000px">

        <GridColumn Field="@nameof(TestModel.CurrentVersion)"
                    Title="Current Version"
                    Editable="true"
                    Filterable="true">

</TelerikGrid>
Hristian Stefanov
Telerik team
 answered on 24 Dec 2024
1 answer
92 views

Hi,
I am reacting to the need for unbind two system solutions for Template RenderFragment of FomItem. If I use standard FormItem, I am getting everything solved - styles, messages, label, ... However just because I need TextArea instead of standard input, the very first thing I am loosing is for in label, because for unknown reason your components have given ID and it cannot be read for that for attribute of label. After losing that standard behaviour, I am also losing error propagating and validations. I am supposed to manually retrieve error messages with TelerikValidationMessage, however for some unknown reason you've enforced Expression for FieldIdentifier and hide the possibility to set FieldIdentifier manually. So I had to derive my custom component, hide your For parameter and set it to "() => default" so it would not trigger null check exception.

Now, why all this. Because I've successfully cloned original Model with all properties and attributes with custom Assembly. I am also able to omit or include ValidationAttribute attributes - thus enabling or disabling validations. And for those templates, I've made RenderFragment<EditModel<TValue>> extension of your Template (I hate Blazor for inability to extend parameters - I had to create a new one - BindTemplate), so I was also able to cover that original model with BindValue property, which has all attributes included and it is also properly notifying EditContext if wrapped value changed - to original FieldIdentifier. So now I can have BindTemplate with not only correct typed binding for any two way binding with property, but also GetValidationMessage ony my EditModel Context, so everything within that template without need to manually do that work. It is up to you, if you want to include my project or create some other form type for that. However, it would be nice, since My system is much more robust and provides binded way for message and its property to be used within the template:

 

<AnetFormItem EditModel="() => this.Is.Your.Previous.For.Attribute">
<BindTemplate Context="model">
<TelerikTextArea @bind-value="model.BindValue">
@model.GetValidationMessage()/* No For here, it is already binded within Context model */
</BindTemplate>
</AnetFormItem>
It seems more logical to me - to derive that BindValue directly form For expression instead making programmer to bind whatever and then figure out the correct MemberExpression for the message. You could also provide RenderFragment for lable on that model and much more - that is meaning of this post ... It is also only logical as this is similar for Grid cell template ...
Dimo
Telerik team
 answered on 23 Dec 2024
1 answer
61 views
I have a TelerikGrid that the first column will open a TelerikWindow with a TelerikUpload. This is so that the user can upload files to the server that will be associated with the object. The object being edited has values that depend on the file being uploaded. For example, the file being uploaded has a File Name. If the File Name already exists, I want to change the name of the file currently being uploaded to include the Revision number at the end of the file name. For example, we have a file on the server named TestFile.pdf, and I am uploading a file named TestFile.pdf. If TestFile.pdf exists, I want to check what the revision of the TestFile.pdf that's already uploaded is, and add it to the end of the file name (TestFile_rev0.pdf). That part is simple, because it's just manipulation of the saved file on the server. However, the new file being uploaded I want to then change the name of it to TestFile_rev1.pdf, and I can do that and save it to the server, but the object in the grid that's currently being added, I need to pass the data to that object being edited, however it will not pass the data. How can we do that?


@page "/SDS"

@using SafetySite.Models;
@using Helpers

@inject SDSModel SDSModel
@inject UserModel UserModel
@inject NavigationManager NavigationManager

<PageTitle>Safety Data Sheets</PageTitle>

<TelerikGrid Data=@SDSItemsList
             FilterMode="GridFilterMode.FilterMenu"
             Sortable="true"
             EditMode="GridEditMode.Inline"
             Height="2000px">

    <GridToolBarTemplate>
        <GridCommandButton Command="Add"  Icon="@SvgIcon.Plus" Enabled="@UserModel.CanEdit()">Add SDS Sheet</GridCommandButton>
    </GridToolBarTemplate>

    <GridColumns>
        <GridColumn Field="@(nameof(SDSModel.FileExists))"  Title="File" Width="120px">

            <EditorTemplate>

                @{
                    var item = context as SDSModel;
                    if(item != null)
                    {
                        <TelerikButton OnClick="@(() => ToggleUploadWindow(item))"
                                       Icon="@SvgIcon.Upload"
                                       Class="btn btn-sm btn-primary">
                            Upload File
                        </TelerikButton>
                    }
                }

            </EditorTemplate>
            
            <Template>

                @{
                    var item = context as SDSModel;
                    if(item != null)
                    {
                        <div class="text-center">
                            <TelerikButton OnClick="@(() => NavigateToViewSDSFile(item.FileName!))"
                                           Class="navlinkgrow">

                                <div class="navlink-content">
                                    <span class="@(item.FileExists ? "text-success" : "text-danger")">
                                        <i class="fa-duotone fa-solid fa-file-pdf fa-2x"></i>
                                    </span>
                                </div>

                            </TelerikButton>
                        </div>

                    }
                }

            </Template>
        </GridColumn>


        <GridColumn Field="@nameof(SDSModel.Title)"
                    Title="Title"
                    Editable="true" />


        <GridColumn Field="@nameof(SDSModel.Revision)"
                    Title="Revision"
                    Editable="true" />


        <GridColumn Field="@nameof(SDSModel.CurrentVersion)"
                    Title="CurrentVersion"
                    Editable="true">

            <Template>
                @{
                    var item = context as SDSModel;
                    if (item != null)
                    {
                        <input type="checkbox" checked="@item.CurrentVersion" disabled />
                    }
                }
            </Template>

        </GridColumn>


        <GridColumn Field="@nameof(SDSModel.CreatedBy)"
                    Title="Created By"
                    Editable="false" />

        <GridColumn Field="@nameof(SDSModel.EditedBy)"
                    Title="Edited By"
                    Editable="false" />

        <GridColumn Field="@nameof(SDSModel.CreationDate)"
                    Title="Creation Date"
                    DisplayFormat="{0:yyyy-MM-dd}"
                    Editable="false" />

        <GridColumn Field="@nameof(SDSModel.EditedDate)"
                    Title="Edit Date"
                    DisplayFormat="{0:yyyy-MM-dd}"
                    Editable="false" />
        
        <GridCommandColumn>
            <GridCommandButton Command="Save"
                               Icon="@SvgIcon.Save"
                               ShowInEdit="true"
                               Enabled="@UserModel.CanEdit()"
                               OnClick="@OnUpdate">
                Update
            </GridCommandButton>

            <GridCommandButton Command="Edit"
                               Icon="@SvgIcon.Pencil"
                               Enabled="@UserModel.CanEdit()">
                Edit
            </GridCommandButton>

            <GridCommandButton Command="Delete"
                               Icon="@SvgIcon.Trash"
                               Enabled="@UserModel.CanEdit()"
                               OnClick="@OnDelete">
                Delete
            </GridCommandButton>

            <GridCommandButton Command="Cancel"
                               Icon="@SvgIcon.Cancel"
                               ShowInEdit="true"
                               Enabled="@UserModel.CanEdit()">
                Cancel
            </GridCommandButton>

        </GridCommandColumn>

    </GridColumns>
</TelerikGrid>


@* THIS TELERIK WINDOW OPENS A POPUP OF A TELERIK FILE MANAGER THAT ALLOWS FOR THE INDIVIDUAL TO PLACE A PDF ASSOCIATED WITH THAT ITEM INTO THE FOLDER *@
<TelerikWindow Width="400px" Height="fit-content" Centered="true" @bind-Visible="@IsUploadFileWindowVisible">
    <WindowTitle>
        <strong>Upload SDS File</strong>
    </WindowTitle>

    <WindowActions>
        <WindowAction Name="Close" OnClick="@(() => IsUploadFileWindowVisible = !IsUploadFileWindowVisible)" />
    </WindowActions>

    <WindowContent>
        <TelerikUpload Multiple="false"
                       SaveUrl="@SaveUrl"
                       RemoveUrl="@RemoveUrl"
                       OnSuccess="@OnFileUploadSuccess"
                       AllowedExtensions="@AllowedExtensions"
                       MaxFileSize="10485760"/>

    </WindowContent>
</TelerikWindow>


@code {

    private bool IsUploadFileWindowVisible { get; set; } = false;
    private List<SDSModel> SDSItemsList = new();
    private SDSModel? CurrentItem { get; set; } = new SDSModel();
    private List<string> AllowedExtensions = new List<string> { ".pdf" };
    private bool CanSaveUpload { get; set; } = false;
    private string SaveUrl = String.Empty;
    private string RemoveUrl = String.Empty;

    public void ToggleUploadWindow(SDSModel item)
    {
        CurrentItem = item;
        SaveUrl = $"{NavigationManager.BaseUri}api/Upload/SavePdf?rev={item.Revision}";
        RemoveUrl = $"{NavigationManager.BaseUri}api/Upload/RemovePdf";
        IsUploadFileWindowVisible = !IsUploadFileWindowVisible;
    }

    private void NavigateToViewSDSFile(string fileName)
    {

        if (!string.IsNullOrEmpty(fileName))
        {
            string fileUrl = $"/SafetyDataSheets/{fileName}";
            NavigationManager.NavigateTo(fileUrl, forceLoad: true);
        }
        else
        {
            Console.WriteLine("No document found for the specified file name.");
        }
    }


    private async Task OnFileUploadSuccess(UploadSuccessEventArgs args)
    {
        if (CurrentItem != null && args.Files.Count > 0)
        {
            var uploadedFile = args.Files[0];
            string fileName = uploadedFile.Name;

            // Check if a file with the same name already exists in the database
            bool fileExists = await SDSModel.FileExistsAsync(fileName);

            if (fileExists)
            {
                var existingItem = await SDSModel.GetSDSItemByFileNameAsync(fileName);
                if(existingItem != null)
                {
                    existingItem.CurrentVersion = false;
                    await SDSModel.UpdateOldSDSItemAsync(existingItem.FileName, UserModel.EmployeeID);

                    CurrentItem.Revision = existingItem.Revision + 1;
                    fileName = $"{Path.GetFileNameWithoutExtension(uploadedFile.Name)}_rev{CurrentItem.Revision}{Path.GetExtension(uploadedFile.Name)}";
                }
            }

            CurrentItem.FileName = fileName;
            CurrentItem.FileExists = true;
            CurrentItem.CurrentVersion = true;
        }
    }

    private async Task OnUpdate(GridCommandEventArgs args)
    {
        var item = args.Item as SDSModel;
        if (item != null)
        {
            item.EditedBy = UserModel.EmployeeID;
            await SDSModel.SaveSDSItemAsync(item);
            SDSItemsList = await SDSModel.GetSDSItemsAsync();
        }
    }

    private async Task OnDelete(GridCommandEventArgs args)
    {
        var item = args.Item as SDSModel;
        if (item != null)
        {
            await SDSModel.DeleteSDSItemAsync(item);
            SDSItemsList = await SDSModel.GetSDSItemsAsync();
        }
    }


    protected override async Task OnInitializedAsync()
    {
        SDSItemsList = await SDSModel.GetSDSItemsAsync();
        await base.OnInitializedAsync();
    }

}

Glenn
Top achievements
Rank 1
Iron
Iron
 answered on 23 Dec 2024
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?