Databinding in Blazor Teleric Grid


Recently I was doing POC demo with Telerik Blazor Grid. It is very powerful and user friendly to developer.

Here is the complete code snippet for data binding in grid

@page "/grid"
<h3>GridDemo</h3>

<TelerikGrid Data="@GridData" SelectionMode="@selectionMode"
             Pageable="true" @bind-SelectedItems="@SelectedItems"
             Sortable="true"
             FilterMode="@GridFilterMode.FilterRow">
    <GridColumns>
        <GridCheckboxColumn SelectAll="@ShowSelectAll"></GridCheckboxColumn>
        <GridColumn Field="Name" Title="Product Name" />
        <GridColumn Field="Price" />
        <GridColumn Field="@(nameof(Product.Released))" />
        <GridColumn Field="@(nameof(Product.Discontinued))" />
    </GridColumns>
</TelerikGrid>
<h2>Selected Items:</h2>
<ul>
    @foreach (Product product in SelectedItems)
    {
        <li>
            @product.Name 
        </li>
    }
</ul>

@code {
    GridSelectionMode selectionMode { get; set; } = GridSelectionMode.Multiple;
    List<Product> GridData { get; set; }
    bool ShowSelectAll => selectionMode == GridSelectionMode.Multiple;
    public IEnumerable<Product> SelectedItems { get; set; } = new List<Product>();

    protected override void OnInitialized()
    {
        GridData = Enumerable.Range(1, 30).Select(x => new Product
            {
                Id = x,
                Name = "Product name " + x,
                Price = (decimal)(x * 3.14),
                Released = DateTime.Now.AddMonths(-x).Date,
                Discontinued = x % 5 == 0
            }).ToList();

        base.OnInitialized();
    }

    void ClearSelection(ChangeEventArgs e)
    {
        Enum.TryParse(e.Value.ToString(), out GridSelectionMode chosenMode);
        selectionMode = chosenMode;
        if (chosenMode == GridSelectionMode.Single)
        {
            Product selectedItem = null;
            if (SelectedItems.Count() > 0)
            {
                selectedItem = SelectedItems.Last();
            }
            var TempItems = new List<Product>();
            if (selectedItem != null)
            {
                TempItems.Add(selectedItem);
            }
            SelectedItems = TempItems.AsEnumerable<Product>();
        }
    }
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public DateTime Released { get; set; }
        public bool Discontinued { get; set; }
    }
}

How to download the XML file on Blazor ?


In my recent project I got the requirement to download the Xml file, I did like this

Step 1: Create the Js folder on wwwroot folder and create download.js file

Step 2: Write Javascript code for download file like this

function BlazorDownloadFile(filename, contentType, content) {
    // Create the URL
    const file = new File([content], filename, { type: contentType });
    const exportUrl = URL.createObjectURL(file);

    // Create the <a> element and click on it
    const a = document.createElement("a");
    document.body.appendChild(a);
    a.href = exportUrl;
    a.download = filename;
    a.target = "_self";
    a.click();

    // We don't need to keep the object URL, let's release the memory
    // On older versions of Safari, it seems you need to comment this line...
    URL.revokeObjectURL(exportUrl);
}

Step 3: Add the file on _layout.cshtml page like this

script src="Js/download.js"></script>

Step 4: On Razor page inject IJSRuntime

@inject IJSRuntime JSRuntime
protected async void SaveReport()
    {
        templateFolderPath = Path.Combine(Environment.ContentRootPath, "wwwroot", @"Payloads\Templates");
        string downloadfolerpath = Path.Combine(Environment.ContentRootPath, "wwwroot", "download");
        int report = Convert.ToInt32(objReporting.TypeOfBrReport);
        int fileType=Convert.ToInt32(objReporting.InputFileType);

        xmlDownloadContent=processReport.ProcessFile(report, fileType, path, templateFolderPath, reportConfig,downloadfolerpath);

        await JSRuntime.InvokeVoidAsync("BlazorDownloadFile", "File.xml", "application/xml", xmlDownloadContent);

    }

File upload syntax using Blazor Synfussion Control


@using JR_PDFtoExcel.Data;
@inject PdfService PdfService

<PageTitle>Schedule F</PageTitle>

<h1>Schedule F</h1>
<SfUploader AllowMultiple="false" AutoUpload="false" AllowedExtensions=".pdf" >
    <UploaderEvents ValueChange="OnChange" OnClear="ClearMsg"></UploaderEvents>
</SfUploader>

@if (LoadMsg == "File is loading...")
{
    <Wave />   
}
@LoadMsg

@code {

    public string? LoadMsg { get; set; }


    private async Task<bool> OnChange(UploadChangeEventArgs args)
    {
        foreach (var file in args.Files)
        {
            LoadMsg = "File is loading...";
            var path = "wwwroot/" + file.FileInfo.Name;
            FileStream filestream = new FileStream(path, FileMode.Create, FileAccess.Write);
            file.Stream.WriteTo(filestream);
            filestream.Close();
            file.Stream.Close();
            LoadMsg = "File loaded...";
            //  call the function to convert PDF to Excel
           //await PdfService.ExcelScheduleF(ExcelfilePath);
        }
         await Task.Delay(1);
         return true;
    }

     private void ClearMsg()
    {
        LoadMsg = "";
    }

}