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

How to add a supporting web api and routing to support databinding in SF Grid on Blazor Server Side?

I see in the documentation when using blazor server side, with entity framework it is reccomended to make a DAL and then a WebAPI that is connected to the SF Grid.

When using Blazor Server side with Entity Framework and never wanting to build it for Blazor Web Assembly... Is that the best way to bind to SF Grid?

More details being discussed in the Stack Overflow question:


Details:

What is the best approach to add a web api as a project to the default ASP.NET Blazor solution? When using visual studio 2019 you no longer get the server and web projects when you select Blazor server on create new solution/project.

I found a way be browsing serveral blogs but it was mentioned that microsoft might dis-continue this.

Looking for the best way.
The reason I need to add an API to an ASP.NET Blazor Side project is to so the SyncFusion DataGrid can bind to it. See: https://blazor.syncfusion.com/documentation/datagrid/data-binding/#entity-framework

Here is what I am thinking of trying:

Use "options.EnableEndpointRouting" approach.

  • Step 1: Create an API folder
  • Step 2: Right Click/Add New/ Controller/Web API Step
  • Modify Startup.cs with:

using Microsoft.AspNetCore.Mvc;

services.AddMvc(options => options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);

app.UseMvcWithDefaultRoute();

Is this considered a future safe or supported way to do it?

Server Side Blazor Created By VS 2019 Wizard:


3 Replies 1 reply marked as answer

VN Vignesh Natarajan Syncfusion Team May 25, 2021 07:28 AM UTC

Hi Victor,  
 
Thanks for contacting Syncfusion support.  
 
Query: “What is the best approach to add a web api as a project to the default ASP.NET Blazor solution? 
 
As per your requirement we have prepared a sample (Blazor Server side) with Syncfusion DataGrid component and bound data to Grid from WebAPI controller using WebAPI adaptor. Refer the below code example  
 
<SfGrid @ref="Grid" TValue="Order" AllowFiltering="true" Toolbar="@(new List<string> {"Add","Edit","Delete","Update","Cancel","Search" })" AllowSorting="true" AllowPaging="true"> 
    <SfDataManager Url="api/Default" Adaptor="Adaptors.WebApiAdaptor"></SfDataManager>     
    <GridEvents OnActionFailure="Fail" TValue="Order"></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="EmployeeID" HeaderText="ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>        
    </GridColumns> 
</SfGrid> 
 
[Route("api/[controller]")]    [ApiController]    public class DefaultController : ControllerBase    {        public OrderDataAccessLayer OrderService = new OrderDataAccessLayer();        // GET: api/Default        [HttpGet]        public async Task<object> Get(int? code)        {            var data = OrderService.GetAllOrders().AsQueryable();            var queryString = Request.Query;. . . .             if (queryString.Keys.Contains("$inlinecount"))            {                StringValues Skip;                StringValues Take;                int skip = (queryString.TryGetValue("$skip"out Skip)) ? Convert.ToInt32(Skip[0]) : 0;                int top = (queryString.TryGetValue("$top"out Take)) ? Convert.ToInt32(Take[0]) : data.Count();                var count = data.Count();                return new { Items = data.Skip(skip).Take(top), Count = count };            }            else            {                return data;            }        } 
 
 
We have integrated both the Grid component and WebAPI controller inside the single application and performed CRUD operation.   
 
 
Note: kindly change the connectionstring of NorthWnd.MDF file in OrderContext.cs file based on MDF file in App_Data folder.  
 
Refer our UG documentation for your reference 
 
 
Please get back to us if you have further queries.  
 
Regards, 
Vignesh Natarajan 
 



VI Victor May 26, 2021 05:17 AM UTC

@Vignesh Natarajan

Thanks so much for your detailed response.

Syncfusion has AWESOME support!!!

 

---

The documentation that I had already reviewed laid out that for the SF grid component to connect to entity framework, a web API was recommended.

My question was really more towards.... If I am using Blazor SERVER NOT Blazor Web Assembly,is there an easier way to connect the SF grid to Entity Framework or a DAL without a Web API in the middle.

 

For some generic fast start cases ( like most I do) I skip the DAL and chose not to use Blazor Web Assembly because I don't want the work involved in writing and maintaining Web APIs.

 

In the Blazor Server setup, can we bind direct to entity framework in someway?

 

I really like DALs and WebAPIs but if you have tons of little tables to get out, you need to save the time in MVP.



VN Vignesh Natarajan Syncfusion Team May 27, 2021 05:29 AM UTC

Hi Victor,  
 
Thanks for the update.  
 
Query: “In the Blazor Server setup, can we bind direct to entity framework in someway? 
 
Yes, we can bind the data from database directly to Grid using Entity Framework and we would like to inform you that CRUD operation needs to be handled in Grid Action events to save the changes properly in the database. So we suggest you to achieve your requirement using OnActionBegin event of Grid. OnActionBegin will be triggered when certain action is initiated, in that event we can save the changes in your database when RequestType is Save.  
 
Refer the below code example.  
 
<SfGrid @ref="Grid" DataSource="@GridData" Toolbar="@(new List<string> { "Add""Edit""Delete""Cancel""Update" })" AllowFiltering="true" AllowSorting="true" AllowPaging="true"> 
    <GridEditSettings AllowAdding="true" AllowDeleting="true" AllowEditing="true" Mode="EditMode.Dialog"></GridEditSettings> 
    <GridEvents OnActionBegin="OnBegin" OnActionComplete="OnComplete" TValue="Order"></GridEvents> 
    <GridColumns> 
        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" Visible="false" IsIdentity="true" IsPrimaryKey="true" TextAlign="TextAlign.Right" Width="120"></GridColumn> 
        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer Name" Width="150"></GridColumn> 
        <GridColumn Field=@nameof(Order.EmployeeID) HeaderText="Id" Width="150"></GridColumn> 
    </GridColumns> 
</SfGrid> 
@code{ 
    SfGrid<Order> Grid { getset; } 
    public IEnumerable<Order> GridData { getset; } 
    protected override void OnInitialized() 
    { 
        GridData = OrderData.GetAllOrders().ToList(); 
    } 
    public void OnComplete(ActionEventArgs<Order> Args) 
    { 
        if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Save || Args.RequestType == Syncfusion.Blazor.Grids.Action.Cancel) 
        { 
            // fetch updated data from service and bind to grid datasource property 
            GridData = OrderData.GetAllOrders().ToList(); 
        } 
    } 
    public void OnBegin(ActionEventArgs<Order> Args) 
    { 
        if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Save// update the changes in Actionbegine event 
        { 
            if (Args.Action == "Add") 
            { 
                //insert the record into database 
                OrderData.AddOrder(Args.Data); 
            } 
            else 
            { 
                //update the existing record 
                OrderData.UpdateOrder(Args.Data); 
            } 
        } 
        else if (Args.RequestType == Syncfusion.Blazor.Grids.Action.Delete) 
        { 
            // delete the record from your database 
            OrderData.DeleteOrder(Args.Data.OrderID); 
        } 
    } 
 
 
For your convenience we have prepared a sample which can be downloaded from below  
 
 
Note: change the connection string in OrderContext.cs file based on NorthWND.MDF file in app_data folder.  
 
Refer our UG documentation for your reference 
 
 
Please get back to us if you have further queries.  
 
Regards, 
Vignesh Natarajan 
 


Marked as answer
Loader.
Live Chat Icon For mobile
Up arrow icon