Blazor Grid - How to connect CRUD operations to custom methods

Hi,

I'm new to Syncfusion and Entity Framework in general, and I'm trying out a few different things to try to familiarize myself with how everything works.

I have a page which has a dropdownlist, which when selected loads a grid based on the selected value of the dropdown. I use a separate repository to get the required data for both the dropdownlist and the grid. I also want the grid to have add and delete functionalities. I've added the corresponding methods to the repository, but couldn't figure out how to connect them to the grid's Add/Delete operations.

I have Add, Delete, Update, Cancel on the grid's toolbar, but as it is right now, only the Delete button is enabled. If I try to edit a row, the Update and Cancel buttons get enabled as well, but the Add button doesn't get enabled at any point. Also, if I select a row and then click the Delete button, it deletes the row at that moment, but if I reload the page, that row is still there. I'm guessing that has something to do with my delete method not being connected to the operation, which is what I don't know how to do.

I tried calling the repository's Add/Delete methods in the OnActionBegin event of the grid, but that doesn't seem to work either.

I've attached the zipped application I've been working on. The UserBuildings page is the one I'm working on. The methods for getting all the data is in the UserBuildingRepository.cs file under the Data folder.

Please let me know how I can link the Add/Delete operations of the grid with the corresponding functions in the repository.

Thanks,
Rajkishan

Attachment: SyncfusionBlazorWebApplication1_3a7793d1.zip

7 Replies

VN Vignesh Natarajan Syncfusion Team March 26, 2020 09:50 AM UTC

Hi Rajkishan,  
 
Greetings from Syncfusion support  
 
Query1: ”but the Add button doesn't get enabled at any point 
 
Add toolbar button will be enabled in Grid only when AllowAdding property of GridEditSettings is enabled. Refer the below code example.  
 
<SfGrid DataSource="@userBuildings" AllowPaging="true" Toolbar="@(new List<string>() { "Add""Delete""Update""Cancel" })"> 
            <GridEvents OnActionBegin="ActionBegin" TValue="UserBuilding"></GridEvents> 
            <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" Mode="EditMode.Batch"></GridEditSettings> 
            . . . . . . .. . .  
        </SfGrid> 
 
 
  
Refer the below UG documentation for your reference 
 
 
Query2: “I tried calling the repository's Add/Delete methods in the OnActionBegin event of the grid, but that doesn't seem to work either. 
 
OnActionBegin event will be triggered only EditMode of the Grid is of Normal / Dialog / Template. Because all these edit mode (except Batch editing) is row based editing. But you have used Batch Edit mode which is cell based editing. So kindly confirm which Edit Mode you want to use.  
 
Also refer our UG documentation for your reference 
 
 
For all other EditMode (except Batch), OnActionBegin event will be triggered with RequestType of its actions (add, edit, delete) as arguments. You can call Add/Delete method from OnActionBegin events. Refer first table.  
 
public void ActionBegin(ActionEventArgs<UserBuildingargs)   {       if (args.RequestType == Syncfusion.Blazor.Grids.Action.Save)       {           //from here you can call the AddMethod of you database.            UserBuildingRepository.AddUserBuilding(args.Data);        }       else if (args.RequestType == Syncfusion.Blazor.Grids.Action.Delete)       {           UserBuildingRepository.RemoveUserBuilding(args.Data);                   }   }
 
 
 
But since you have used Batch editing we suggest you to achieved your requirement using OnBatchSave event of Grid to save the changes in your database. Refer the below code example.  
 
@using Newtonsoft.Json         <SfGrid DataSource="@userBuildings" AllowPaging="true" Toolbar="@(new List<string>() { "Add""Delete""Update""Cancel" })">            <GridEvents OnBatchSave="Save" OnActionBegin="ActionBegin" TValue="UserBuilding"></GridEvents>. . . . . . . . . . . .        </SfGrid>@code {    public string DropVal;. . . . . . . . . .    public async Task Save(BeforeBatchSaveArgs Args)    {        var BatchChanges = JsonConvert.DeserializeObject<Dictionary<stringobject>>(JsonConvert.SerializeObject(Args.BatchChanges));        foreach (var batches in BatchChanges)        {            if (batches.Key == "addedRecords")            {                var AddedRecords = JsonConvert.DeserializeObject<List<UserBuilding>>(JsonConvert.SerializeObject(batches.Value));                for (var i = 0; i < AddedRecords.Count; i++)                {                    UserBuildingRepository.AddUserBuilding(AddedRecords[i]);                }            }            else if (batches.Key == "deletedRecords")            {                var DeletedRecords = JsonConvert.DeserializeObject<List<UserBuilding>>(JsonConvert.SerializeObject(batches.Value));                for (var i = 0; i < DeletedRecords.Count; i++)                {                    UserBuildingRepository.RemoveUserBuilding(DeletedRecords[i]);                }            }        }    }}
 
 
 
Refer our UG documentation for your reference 
 
 
Kindly get back to us if you have further queries.  
 
Regards, 
Vignesh Natarajan. 
   
 
 
 



RR Rajkishan Rajappan March 26, 2020 06:15 PM UTC

Hi Vignesh,

I did forget to set the AllowAdding property to true. But yes, both of your solutions worked perfectly for me (I set the EditMode to Normal). Thank you for that!

I did have one more question though. When someone adds a new building in the grid and try to save it, I check if the building is already available in the grid, and if so, show a dialog to the user asking them to select a different building and return, instead of calling the function to save the new row. This is the code I use for that:

if (args.RequestType == Syncfusion.Blazor.Grids.Action.Save)
        {
            int buildingid = args.Data.BuildingId;

            if (userBuildings.Exists(x => x.BuildingId == buildingid))
            {
                isDialogVisible = true;
                return;
            }

            UserBuilding ub = new UserBuilding();
            ub.BuildingId = args.Data.BuildingId;
            ub.UserId = userIdInt;
            UserBuildingRepository.AddUserBuilding(ub);
        }

However, when I do this, the newly added row is still visible in the grid until I reload the page. I tried calling StateHasChanged() after setting isDialogVisible as true and before return, but it still persists. How do I reset the grid to not show the newly added row if I don't want it to be added?

Thanks,
Rajkishan


VN Vignesh Natarajan Syncfusion Team March 27, 2020 10:29 AM UTC

Hi Rajkishan,  
 
Thanks for the update.  
 
Query: “when I do this, the newly added row is still visible in the grid until I reload the page. 
 
We have understood your requirement (prevent from adding duplicate records) and we suggest you to achieve your requirement by cancelling the default action using Args.Cancel.  
 
Refer the below code example 
 
public void ActionBegin(ActionEventArgs<UserBuildingargs) 
    { 
        if (args.RequestType == Syncfusion.Blazor.Grids.Action.Save) 
        { 
            int buildingid = args.Data.BuildingId; 
  
            if (userBuildings.Exists(x => x.BuildingId == buildingid)) 
            { 
                isDialogVisible = true; 
                  // while returning set Args.Cancel as true.  
                Args.Cancel = true// prevent the default action 
                return; 
            } 
  
            UserBuilding ub = new UserBuilding(); 
            ub.BuildingId = args.Data.BuildingId; 
            ub.UserId = userIdInt; 
            UserBuildingRepository.AddUserBuilding(ub); 
        } 
    } 
 
  
Kindly get back to us if you have further queries.   
 
Regards, 
Vignesh Natarajan. 



RR Rajkishan Rajappan March 27, 2020 04:02 PM UTC

Hi Vignesh,

Thanks for your response! After I sent out the previous reply, I did try args.Cancel = true, and it does reset the grid to not show the newly added row. However, when I do that and return, the Update and Cancel buttons stay enabled, and Add and Delete buttons stay disabled until I reload the page or click Cancel. Is it possible to reset that as well?

Thanks,
Rajkishan


RN Rahul Narayanasamy Syncfusion Team March 30, 2020 02:12 PM UTC

  
Hi Rajkishan, 

Thanks for the update. 

We have validated your query and you can resolve the reported problem by calling CloseEdit method of Grid after setting Args.Cancel. Find the below code snippets for your reference. 

[code snippets] 
<SfGrid DataSource @ref=”Grid”="@userBuildings" AllowPaging="true" Toolbar="@(new List<string>() { "Add""Delete""Update""Cancel" })"> 
            <GridEvents OnActionBegin="ActionBegin" TValue="UserBuilding"></GridEvents> 
            <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" Mode="EditMode.Batch"></GridEditSettings> 
            . . . . . . .. . .  
        </SfGrid> 

@code {  EjsGrid<Order> Grid { getset; }    public string DropVal;. . . . . . . . . .
    public async Task  ActionBegin(ActionEventArgs<UserBuildingargs) 
    { 
        if (args.RequestType == Syncfusion.Blazor.Grids.Action.Save) 
        { 
            int buildingid = args.Data.BuildingId; 
 
            if (userBuildings.Exists(x => x.BuildingId == buildingid)) 
            { 
                isDialogVisible = true; 
                  // while returning set Args.Cancel as true.  
                Args.Cancel = true// prevent the default action 
                await Grid.CloseEdit(); // cancel the editing 
                return; 
            } 
 
            UserBuilding ub = new UserBuilding(); 
            ub.BuildingId = args.Data.BuildingId; 
            ub.UserId = userIdInt; 
            UserBuildingRepository.AddUserBuilding(ub); 
        } 
    } 
}

Please get back to us if you need further assistance. 

Regards, 
Rahul 
 



RR Rajkishan Rajappan March 30, 2020 05:49 PM UTC

Hi Rahul,

Yup that works perfectly! Thanks a lot for all your assistance.

Rajkishan


RN Rahul Narayanasamy Syncfusion Team March 31, 2020 04:55 AM UTC

Hi Rajkishan, 

Thanks for the update. 

We are happy to hear that the provided solution was helpful to achieve your requirement. Please get back to us if you need further assistance. 

Regards, 
Rahul 


Loader.
Up arrow icon