We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Datagrid not reflectiong changes when data is changed using signalr

@page "/"


@inject IStockService _StockService

@inject ICartService _CartService

@inject ILocalStorageService _LocalStorageService

@inject NavigationManager _NavgigationManager

@inject IJSRuntime _JsRuntime



<h3 class="card-title text-primary mb-3 ml-3">Avilable Products </h3>


@if (IsLoading)

{

    <div class="text-center">

        <img src="images/ajax-loader.gif">

    </div>

}

else

{

    @if (IsAddToCart)

    {

        <SfDialog Width="700px" ShowCloseIcon="true" IsModal="true" @bind-Visible="IsAddToCart">

            <DialogTemplates>

                <Header>Ading To Shopping Cart</Header>

                <Content>

                    <div class="col-12">

                        <div class="row pt-3">

                            <div class="col-2">

                                <label>Quantity:</label>

                            </div>

                            <div class="col-4">

                                <Syncfusion.Blazor.Inputs.SfNumericTextBox TValue="double" Min="10" @bind-Value="shoppingcart.Count">


                                </Syncfusion.Blazor.Inputs.SfNumericTextBox>

                            </div>

                        </div>

                    </div>

                </Content>

                <FooterTemplate>

                    <button class="btn btn-danger" @onclick="CancleShoppingCart">Cancel</button>

                    <button class="btn btn-secondary" @onclick="AddToCart">Add</button>

                </FooterTemplate>

            </DialogTemplates>

        </SfDialog>

    }

    <SfGrid @ref="@stockgrid" DataSource="@stock" AllowPaging="true" AllowFiltering="true" AllowSorting="true">

        <GridEditSettings AllowAdding="false" AllowEditing="false" ShowDeleteConfirmDialog="false" AllowDeleting="false"></GridEditSettings>

        <GridEvents CommandClicked="HandleToCart" TValue="StockDTO"></GridEvents>

        <GridFilterSettings Type="Syncfusion.Blazor.Grids.FilterType.Menu"></GridFilterSettings>

        <GridPageSettings PageSize="15" PageCount="5" PageSizes="true"></GridPageSettings>

        <GridColumns>

            <GridColumn IsPrimaryKey="true" AllowAdding="false" Field=@nameof(StockDTO.Id) HeaderText="ID"></GridColumn>

            <GridColumn AllowEditing="false" Field=@nameof(StockDTO.Product) HeaderText="Product"></GridColumn>

            <GridColumn AllowEditing="false" Field=@nameof(StockDTO.ProductCode) HeaderText="Product Code"></GridColumn>

            <GridColumn AllowEditing="false" Field="@nameof(StockDTO.Supplier)" HeaderText="Supplier"></GridColumn>

            <GridColumn AllowEditing="false" Field="@nameof(StockDTO.SellingPrice)" HeaderText="Selling Price"></GridColumn>

            <GridColumn AllowEditing="false" Field="@nameof(StockDTO.Quantity)" HeaderText="Quantity"></GridColumn>

            <GridColumn HeaderText="Add To Cart" TextAlign=TextAlign.Center Width="150">

                <GridCommandColumns>

                    <GridCommandColumn ButtonOption="@(new CommandButtonOptions() { IconCss = "bi bi-cart", CssClass = "e-flat" })" Title="Cart"></GridCommandColumn>

                </GridCommandColumns>

            </GridColumn>

        </GridColumns>


    </SfGrid>

}


@code {

    private IEnumerable<StockDTO> stock { get; set; } = new List<StockDTO>();

    private ShoppingCart shoppingcart { get; set; } = new ShoppingCart();

    private SfGrid<StockDTO> stockgrid { get; set; } = new SfGrid<StockDTO>();

    private HubConnection _Connection;

    public bool IsLoading { get; set; }

    public bool IsAddToCart { get; set; }

    public bool IsAddToCartOperationOngoing;

    public bool IsAddToCartOperationExecuting;

    public bool IsNormalStatus { get; set; } = true;


    public void CancleShoppingCart()

    {

        IsAddToCart = false;

        IsAddToCartOperationOngoing = false;

    }


    public async void AddToCart()

    {

        IsAddToCart = false;

        _NavgigationManager.NavigateTo(_NavgigationManager.Uri, forceLoad: true);

    }


    public void HandleToCart(CommandClickEventArgs<StockDTO> args)

    {

        IsAddToCart = true;

        shoppingcart.Product = args.RowData.Product;

        shoppingcart.Price = args.RowData.SellingPrice;

    }


    private async Task LoadStock()

    {

        IsLoading = true;

        StateHasChanged();

        _Connection = new HubConnectionBuilder().WithUrl("https://localhost:44365/DataChanged").WithAutomaticReconnect().Build();

        _Connection.On("DataChangedAcknowledgement",async () =>

        {

            stock = await _StockService.GetAll();

            stockgrid.DataSource = stock;

            await stockgrid.Refresh().ConfigureAwait(true);

        });


        try

        {

            await _Connection.StartAsync();

        }

        catch (Exception ex)

        {

            await _JsRuntime.ToastrError(ex.Message);

        }


        stock = await _StockService.GetAll();

        IsLoading = false;

        StateHasChanged();

    }


    protected override async Task OnAfterRenderAsync(bool firstRender)

    {

        if (firstRender)

        {

            await LoadStock();

        }


    }

}


4 Replies

MS Monisha Saravanan Syncfusion Team December 28, 2022 12:51 PM UTC

Hi Saiman,


Greetings from Syncfusion support.


Query: “Datagrid not reflectiong changes when data is changed using signalr”


We have checked your query and we would like to inform that based on the request type in ActionComplete event we should update the Grid to reflect the changes. We have prepared an simple sample as per your shared reference. Kindly check the below attached sample for additional information.


Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/BlazorServerSignalRApp960318352.zip


<SfGrid @ref="Grid" DataSource="@Forecasts" AllowPaging="true" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Cancel", "Update" })">

    <GridEvents OnActionComplete="ActionComplete" TValue="WeatherForecast"></GridEvents>

    <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true"></GridEditSettings>

    <GridColumns>

 

    </GridColumns>

</SfGrid>

 

@code {

public async Task ActionComplete(ActionEventArgs<WeatherForecast> Args)

    {

        if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Save)

        {

            await ForecastService.UpdateForecastAsync(Args.Data);

            if (IsConnected) await Send();

        }

    }

async Task Send() =>

        await hubConnection.SendAsync("SendMessage");

}



If you still face difficulties then kindly share the below details at your end.


  1. Share us the video demonstration of the issue.
  2. If possible share us the simple issue reproducing sample or try to reproduce the reported issue on the above mentioned sample.


Above requested details will be very helpful in validating the reported query at our end and provide solution as early as possible.


Regards,

Monisha




SA Saiman replied to Monisha Saravanan December 29, 2022 12:08 AM UTC



SA Saiman December 29, 2022 12:19 AM UTC

I have a blazer server app in which when data is changed a signalR connection I sent  to all the clients. Hence, the client is a different app when it receives a hub connection and updates the stock via API and when I call refresh grid no changes are reflected in the gird. Still, when I force reload the page those changes are reflected as shown In the video so I don't want to force reload the page is there any solution for it.


Regards,

Saiman




MS Monisha Saravanan Syncfusion Team December 29, 2022 12:03 PM UTC

Hi Saiman,


We suspect that you are facing issues with Grid refresh instead of calling Grid refresh we suggest you to fetch and assign the datasource again to the DataSource property of the Grid. So that it will reflect properly with the new Dataset.


Also we suggest you to update the service based on the changed data in the OnActionComplete event of DataGrid. So that it updates the service once the data is updated in Grid.


Kindly check the below sample for your reference. It will refresh the Grid when the data is updated.


Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/BlazorServerSignalRApp960318352.zip


Please let us know if you have any concerns.


Loader.
Up arrow icon