How to CRUD Syncfusion Blazor Grid from a ComponentBase Class

Hi,

I have the following component with PersonBaseClass where I am injecting a service class that calls into a web api. How do I about handling the Create, Update and Delete from the PersonBase class. 

@page "/people"
@using EngagePortal.Shared

@inherits PersonBase
 

 

using EngagePortal.ServerApp.Services;
using EngagePortal.Shared;
using Microsoft.AspNetCore.Components;
using Syncfusion.Blazor;
using Syncfusion.Blazor.Grids;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EngagePortal.ServerApp.Pages
{
    public class PersonBase : ComponentBase 
    {
        [Inject]
        IPersonService PersonDataService { get; set; }

        protected SfGrid Grid;

        protected IEnumerable People = new List();
        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
           if(firstRender)
            {
                People = await PersonDataService.GetPeople();
                StateHasChanged();
            }
        }
 

    }
}

Here is the PersonDataService class

public class PersonDataService : IPersonService
    {
        private readonly HttpClient _httpClient;
        public PersonDataService(HttpClient httpClient)
        {
            _httpClient = httpClient;

        }

        public async Task AddPerson(AzurePerson person)
        {
            var personJson =
               new StringContent(JsonSerializer.Serialize(person), Encoding.UTF8, "application/json");

            var response = await _httpClient.PostAsync("api/people", personJson);

            if (response.IsSuccessStatusCode)
            {
                var newperson= await JsonSerializer.DeserializeAsync(await response.Content.ReadAsStreamAsync(), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });


                return newperson;
            }

            return false;
        }

        public async Task DeletePerson(string id)
        {
            await _httpClient.DeleteAsync($"api/people/{id}");
        }

        public async Task> GetPeople()
        {
            return await JsonSerializer.DeserializeAsync>
                (await _httpClient.GetStreamAsync($"api/people"), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
        }

        public async Task GetPerson(string id)
        {
            return await JsonSerializer.DeserializeAsync
            (await _httpClient.GetStreamAsync($"api/people/{id}"), new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
        }

        public async Task UpdatePerson(AzurePerson person)
        {
            var personJson =
             new StringContent(JsonSerializer.Serialize(person), Encoding.UTF8, "application/json");

            await _httpClient.PutAsync("api/people", personJson);
        }


    }


1 Reply

VN Vignesh Natarajan Syncfusion Team May 8, 2020 12:26 PM UTC

Hi Yassin,  
 
Greetings from Syncfusion support.  
 
Query: “How do I about handling the Create, Update and Delete from the PersonBase class.  
 
From your query we understand that you want to perform CRUD operation in WebAPI service from DataGrid. We Suggest you to achieve your requirement using OnActionBegin event of the Grid. Refer the below code example.  
 
<SfGrid @ref="Grid" DataSource="@Data" TValue="Orders" AllowFiltering="true" Toolbar="@(new List<string> {"Add","Edit","Delete","Update","Cancel","Search" })" AllowSorting="true" AllowPaging="true"> 
    <GridFilterSettings Type="Syncfusion.Blazor.Grids.FilterType.Menu"></GridFilterSettings> 
    <GridEvents OnActionBegin="ActionBeginHandler" TValue="Orders"></GridEvents> 
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true"></GridEditSettings> 
    <GridColumns> 
        <GridColumn Field="OrderID" HeaderText="Order ID" IsPrimaryKey="true" TextAlign="TextAlign.Right" Width="120"></GridColumn> 
        <GridColumn Field="CustomerID" HeaderText="Customer Name" Width="150"></GridColumn> 
        <GridColumn Field="Freight" HeaderText="Freight" Format="C2" TextAlign="TextAlign.Right" EditType="EditType.NumericEdit" Width="120"></GridColumn> 
        <GridColumn Field="OrderDate" HeaderText="Freight" TextAlign="TextAlign.Right" EditType="EditType.DatePickerEdit" Type="ColumnType.DateTime" Width="120"></GridColumn> 
    </GridColumns> 
</SfGrid> 
 
@code{ 
    SfGrid<Orders> Grid { getset; } 
    List<Orders> Data { getset; } 
    protected override async Task OnInitializedAsync() 
    { 
        Data = await OrderData.GetPeople(); 
    } 
    public async void ActionBeginHandler(ActionEventArgs<OrdersArgs) 
    { 
        if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Save) 
        { 
            if (Args.Action == "add") 
            { 
                await OrderData.InsertOrderAsync(Args.Data); 
            } 
            else 
            { 
                await OrderData.UpdateOrderAsync(Args.Data.OrderID.ToString(), Args.Data); 
            } 
        } 
        if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Delete) 
        { 
            await OrderData.DeleteOrderAsync(Args.Data.OrderID.ToString()); 
        } 
    } 
} 
 
 
 
In event arguments we can different certain actions based on the RequestType variable. Based on that we have called certain actions in service with different actions.  
 
[OrderService.cs file] 
 
public class OrderService   {       private readonly HttpClient _httpClient;       public OrderService(HttpClient httpClient)       {           _httpClient = httpClient;        }       string baseUrl = "https://localhost:44314/";       public async Task<List<Orders>> GetPeople()       {            var json = await _httpClient.GetStringAsync($"{baseUrl}api/Default");           return JsonConvert.DeserializeObject<List<Orders>>(json);        }       public async Task<HttpResponseMessageInsertOrderAsync(Orders value)       {                      return await _httpClient.PostAsync($"{baseUrl}api/Default"getStringContentFromObject(value));       }       public async Task<HttpResponseMessageUpdateOrderAsync(string idOrders value)       {                      return await _httpClient.PutAsync($"{baseUrl}api/Default/{id}"getStringContentFromObject(value));       }        public async Task<HttpResponseMessageDeleteOrderAsync(string id)       {                      return await _httpClient.DeleteAsync($"{baseUrl}api/Default/{id}");       }       private StringContent getStringContentFromObject(object obj)       {           var serialized = JsonConvert.SerializeObject(obj);           var stringContent = new StringContent(serializedEncoding.UTF8, "application/json");           return stringContent;       }          }
 
 
 
For your convenience we have prepared a sample which can be downloaded from below  
 
Kindly refer our UG documentation for your reference 
 
 
Please get back to us if you have further queries.  
 
Regards,
Vignesh Natarajan
 
 


Loader.
Up arrow icon