In this blog post, we are going through the step-by-step procedure to connect Syncfusion Blazor DataGrid with an MS SQL Server database using Entity Framework Core and perform CRUD operations in a Blazor WebAssembly application.
To demonstrate CRUD operations in the Syncfusion Blazor DataGrid component, we are going to create a simple library book management application. The final code can be found in this GitHub repository.
Prerequisite software
The following software is needed:
- Visual Studio 2019 v16.8.0 Preview 3.0 or later
- .NET SDK 5.0 RC2 or later
- SQL Server 2017
Create the database
First things first, create a Library database and a table named Book to hold a list of books:
- Open SQL Server 2017.
- Create a new database named Library.
- Right-click on the created database and select New Query.
- Use the following SQL query to create a table named Book.
Create Table Book( Id BigInt Identity(1,1) Primary Key Not Null, Name Varchar(200) Not Null, Author Varchar(100) Not Null, Quantity int, Price int Not Null, Available bit)
Now the Book table design will look as follows.
Create a Blazor WebAssembly application
Open Visual Studio 2019 Preview, select Create a New Project, select Blazor App, and then click Next.
In the next window, provide the project name LibraryManagement and click Create.
Now select the Blazor WebAssembly App project template and select the ASP.NET Core hosted check box. Click Create to create an ASP.NET Core-hosted application.
Explore the best and most comprehensive Blazor UI components library in the market.
When exploring the created application, you can see three projects under one solution.
LibraryManagement.Client: Contains page UI components that will be rendered in the browser.
LibraryManagement. Server: Contains the server-side code such as DB-related operations and Web API.
LibraryManagement.Shared: Contains the shared code, such as model classes, that can be accessed by both client and server.
Creating DbContext and model class
Now we are going to scaffold DbContext and model classes from the existing Library database. To perform scaffolding and work with SQL Server database in our application, we need to install the following NuGet packages.
Run the following commands in the Package Manager Console:
- Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.0.0: This package creates database context and model classes from the database.
- Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 3.0.0: The database provider that allows Entity Framework Core to work with SQL Server.
Once these packages are installed, we can scaffold DbContext and model classes. Run the following command in the Package Manager Console under the LibraryManagement.Server project.
|
This scaffolding command contains the following details for creating DbContext and model classes for the existing database and its tables:
- Connection string: Server=localhost;Database=Library;Integrated Security=True
- Data provider: EntityFrameworkCore.SqlServer
- Output directory: -OutputDir Models
After running this command, LibraryContext.cs and Book.cs files will be created in the LibraryManagement.Server.Models folder as follows.
We can see that the LibraryContext.cs file contains the connection string details in the OnConfiguring method.
Syncfusion’s Blazor components suite is the expert’s choice for building modern web apps.
It is not recommended to have a connection string with sensitive information in the LibaryContext.cs file, so move the connection string to the appsettings.json file.
Now the DbContext must be configured using a connection string and registered as a scoped service using the AddDbContext method in Startup.cs.
Creating a data access layer
The application is now configured to connect with the Library database using Entity Framework. Now it’s time to consume data from the Library database. To do so, we need a Web API controller to serve data from DbContext to the Blazor application.
As the Blazor WebAssembly application runs in the same security sandbox as JavaScript, direct access to databases is not possible. Therefore, Web API is required to consume data from databases.
To create a Web API controller, right-click on the Controller folder in Server project and select Add -> New Item -> API controller with read/write actions. We are naming this controller BooksController as it returns Book table records. Now replace the Web API controller with the following code, which contains code to handle CRUD operations in the Book table.
using LibraryManagement.Server.Models; using Microsoft.AspNetCore.Mvc; using System.Linq; using LibraryManagement.Shared.Models; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace LibraryManagement.Server.Controllers { [Route("api/[controller]")] [ApiController] public class BooksController : ControllerBase { private LibraryContext _context; public BooksController(LibraryContext context) { _context = context; } // GET: api/<BooksController> [HttpGet] public object Get() { return new { Items = _context.Books, Count = _context.Books.Count() }; } // POST api/<BooksController> [HttpPost] public void Post([FromBody] Book book) { _context.Books.Add(book); _context.SaveChanges(); } // PUT api/<BooksController> [HttpPut] public void Put(long id, [FromBody] Book book) { Book _book = _context.Books.Where(x => x.Id.Equals(book.Id)).FirstOrDefault(); _book.Name = book.Name; _book.Author = book.Author; _book.Price = book.Price; _book.Quantity = book.Quantity; _book.Available = book.Available; _context.SaveChanges(); } // DELETE api/<BooksController> [HttpDelete("{id}")] public void Delete(long id) { Book _book = _context.Books.Where(x => x.Id.Equals(id)).FirstOrDefault(); _context.Books.Remove(_book); _context.SaveChanges(); } } }
Add Syncfusion Blazor package
Before adding Syncfusion Blazor components to the application, we need to move the Book.cs file to the LibraryManagement.Shared project, as it is required in both client and server projects.
To add Syncfusion components to the project, right-click on Dependencies and select Manage NuGet Packages.
In the Browse tab, find and install the Syncfusion.Blazor NuGet package.
Open the _Import.razor file and add the following namespaces, which are required to use Syncfusion Blazor components in this application.
@using Syncfusion.Blazor @using Syncfusion.Blazor.Grids @using Syncfusion.Blazor.Data
Every property of the Syncfusion Blazor components is completely documented for easy use.
Open the Program.cs file and register the Syncfusion service in the Main method as follows.
using Syncfusion.Blazor; namespace LibraryManagement.Client { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("#app"); builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); builder.Services.AddSyncfusionBlazor(); await builder.Build().RunAsync(); } } }
Themes provide life to components. Syncfusion Blazor has different themes:
- Bootstrap4
- Material
- Office 365
- Bootstrap
- High contrast
In this demo application, I will be using the Bootstrap4 theme. To add the theme, open the wwwroot/index.html file and add the following CSS reference code.
<link href="_content/Syncfusion.Blazor/styles/bootstrap4.css" rel="stylesheet" />
Add Syncfusion Blazor DataGrid component
In previous steps, we have successfully configured the Syncfusion Blazor package in the application. Now we can add the grid component to the Index.razor page. TValue in the SfGrid defines the model type the grid is bound to. We are creating a grid from the Book table, so we have used the TValue of Book.
@using LibraryManagement.Shared.Models <SfGrid TValue="Book"> </SfGrid>
- Grid columns can be defined using the GridColumn component. We are going to create columns using the following code.
@using LibraryManagement.Shared.Models <SfGrid TValue="Book"> <GridColumns> <GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" Visible="false"></GridColumn> <GridColumn Field="@nameof(Book.Name)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Author)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Quantity)" Width="90" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Price)" Width="90" Format="C2" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Available)" DisplayAsCheckBox="true" Width="70"></GridColumn> </GridColumns> </SfGrid>
Let`s look at the properties and their usage:
- Field specifies the column name of the Book table to display in the grid column.
- IsPrimaryKey specifies the given column is a primary key column. Here, the Id column is a primary key column.
- Visible specifies the column visibility. Setting it as false will hide the column on the user end.
- Width specifies the column width.
- Format helps to format numbers, currencies, and dates for a particular culture. Here, we have formatted the Price column.
- DisplayAsCheckBox renders check boxes in cells and sets the check state based on the property value. Here, the Available column is rendered as a check box column.
To consume data from Web API, use the SfDataManager component. SfDataManager provides flexible data binding capability to Syncfusion components. It has various built-in adaptors to communicate with different types of data sources.
Here, we are using Web API to provide data, so we choose WebApiAdaptor as the data adaptor for SfDataManager.
@using LibraryManagement.Shared.Models <SfGrid TValue="Book"> <SfDataManager Url="/api/Books" Adaptor="Adaptors.WebApiAdaptor"></SfDataManager> <GridColumns> <GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" Visible="false"></GridColumn> <GridColumn Field="@nameof(Book.Name)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Author)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Quantity)" Width="90" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Price)" Width="90" Format="C2" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Available)" DisplayAsCheckBox="true" Width="70"></GridColumn> </GridColumns> </SfGrid>
Explore the different application UIs developed using Syncfusion Blazor components.
We can enable editing in the grid component using the GridEditSettings property. DataGrid provides various modes for editing, such as inline/normal, dialog, and batch editing. Here, we are using the inline edit mode and the Toolbar property to show tool bar items to edit.
@using LibraryManagement.Shared.Models <SfGrid TValue="Book" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })"> <SfDataManager Url="/api/Books" Adaptor="Adaptors.WebApiAdaptor"></SfDataManager> <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true"></GridEditSettings> <GridColumns> <GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" Visible="false"></GridColumn> <GridColumn Field="@nameof(Book.Name)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Author)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Quantity)" Width="90" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Price)" Width="90" Format="C2" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Available)" DisplayAsCheckBox="true" Width="70"></GridColumn> </GridColumns> </SfGrid>
On running the application, we will see the grid as follows.
Insert a row
To insert a new row, click the Add toolbar button. The new record edit form will look similar to the following screenshot.
Clicking the Update toolbar button will insert the record in the Book table by calling the POST method of the Web API.
Update a row
To edit a row, select any row and then click the Edit toolbar button. The edit form will look like the following.
Now we change the Quantity column value from 10 to 9 and click the Update toolbar button. We update the record in the Book table by calling the PUT method of the Web API. The resultant grid will look like the following.
Delete a row
To delete a row, select any row and then click the Delete toolbar button. The deleting operation will send a DELETE request to the Web API with the selected record`s primary key value to remove the corresponding record from the Book table.
See how Syncfusion Blazor components can be transformed into beautiful and efficient applications.
Enable data validation
It is common to validate user input before saving it to the database. Blazor DataGrid provides a built-in validation system to validate user input. Validation by column can be done using the GridColumn.ValidationRules property.
In the following code:
- We have enabled required validation for Quantity, so we cannot leave that field empty during add and edit operations.
- Range validation is enabled for the Price column so the price value entered must be between 1 and 1,000.
@using LibraryManagement.Shared.Models <SfGrid TValue="Book" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })"> <SfDataManager Url="/api/Books" Adaptor="Adaptors.WebApiAdaptor"></SfDataManager> <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true"></GridEditSettings> <GridColumns> <GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" Visible="false"></GridColumn> <GridColumn Field="@nameof(Book.Name)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Author)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Quantity)" ValidationRules="@(new ValidationRules(){ Required = true })" Width="90" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Price)" ValidationRules="@(new ValidationRules(){ Range = new double[]{ 1, 1000 } })" Width="90" Format="C2" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Available)" DisplayAsCheckBox="true" Width="70"></GridColumn> </GridColumns> </SfGrid>
Now validation error messages will be shown in the grid.
Handling exceptions
Proper error handling helps you catch and react to the errors thrown in an application. Blazor DataGrid provides an action failure event to catch errors and handle them in a graceful way. OnActionFailure event can be used to capture unexpected errors during grid actions and editing operations.
@using LibraryManagement.Shared.Models <SfGrid TValue="Book" Toolbar="@(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" })"> <SfDataManager Url="/api/Books" Adaptor="Adaptors.WebApiAdaptor"></SfDataManager> <GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true"></GridEditSettings> <GridColumns> <GridColumn Field="@nameof(Book.Id)" IsPrimaryKey="true" Visible="false"></GridColumn> <GridColumn Field="@nameof(Book.Name)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Author)" Width="150"></GridColumn> <GridColumn Field="@nameof(Book.Quantity)" ValidationRules="@(new ValidationRules(){ Required = true })" Width="90" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Price)" ValidationRules="@(new ValidationRules(){ Range = new double[]{ 1, 1000 } })" Width="90" Format="C2" TextAlign="TextAlign.Right"></GridColumn> <GridColumn Field="@nameof(Book.Available)" DisplayAsCheckBox="true" Width="70"></GridColumn> </GridColumns> <GridEvents TValue="Book" OnActionFailure="Failure"></GridEvents> </SfGrid> @code{ private void Failure(FailureEventArgs e) { Console.WriteLine(e.Error.Message); Console.WriteLine(e.Error.StackTrace); } }
Syncfusion Blazor components can be transformed into stunning and efficient web apps.
Conclusion
In this blog, we have learned how to create a Blazor WebAssembly application, include the Blazor DataGrid component, and perform CRUD operations using Entity Framework Core.
Syncfusion provides more than 65 high-performance, lightweight, modular, and responsive Blazor UI controls such as DataGrid, Charts, and Scheduler to ease the work of developers. Check them out!
If you have any questions, please let us know in the comments section below. You can also contact us through our support forum, support portal, or feedback portal. We are always happy to assist you!
Comments (26)
I did this tutorial and is fast and easy do a CRUD with Syncfusion Blazor UI component library.
That was great, but why did you point your SfGrid TValue=”Book” to use “LibraryManagement.Shared.Models”, instate of “LibraryManagement.Shared”?
In the “Add Syncfusion Blazor package” section you could see that I have moved Book.cs from Server project to Shared project. And also changed the namespace from “LibraryManagement.Server.Models” to “LibraryManagement.Shared.Models”. Now Book class is available under the namespace “LibraryManagement.Shared.Models” hence i am referring to this namespace to use Book class in SfGrid.
The Book class is directly an EF entity class. There is no intermediate DTO class. Do you support this solution in a real life application, or it is better to have real DTO classes there?
Thanks for the tutorial. However, this would have been way more helpful if it included identity. I tried using identity with this tutorial and it just does not work….
In the post, the Id field of the Book table is an identity column. You could see the SQL script used to create the Book table from this link (https://github.com/SyncfusionExamples/blazor-wasm-datagrid-efcore-crud/blob/main/SQL%20Script/book-table.sql#L2).
I believe that you are facing “Unable to add new record in empty grid when using remote data source” issue. If the table already contains some data then add form will display properly. If you are facing this issue, I have created the bug report for this issue the fix will be available at the end of Feb 2021.
https://www.syncfusion.com/feedback/22008.
If you are facing any other issue please share those details for further validation.
When the table in the database is empty, I cannot Add a row. When I manually insert a row on the sql server, it then behaves as expected.
While having a blank table would be very rare for me, I would like to understand why this happens and how to avoid it. It is also *not* what the article describes.
I tried both following the steps and running the complete solution from Github. (Note that my computer already has 18.4 of SyncFusion, and that the GitHub repo is using RC1 of a lot of the products. However, I don’t think that’s the issue).
Yes, I am able to see the problem in the v18.4.*. I have created feedback bug report to fix this issue. The fix would be available by the end of February 2021. Please refer this feedback report link for follow up.
https://www.syncfusion.com/feedback/22008
The first time I run the GitHub code I had the grid displayed OK but I tried to add a record & it crashed.
(saw previous posts) & I tried also having already one record in the DB but now I got the following error as soon as I start the project.
System.ArgumentNullException
HResult=0x80004003
Message=Value cannot be null. (Parameter ‘input’)
……..
This exception was originally thrown at this call stack:
[External Code]
Me,too System.ArgumentNullException: ‘Value cannot be null. Arg_ParamName_Name’
When I Run it.
Unfortunately, I am unable to reproduce this problem. This might be due to the RC version of .Net packages in the application. I have now upgraded the application to Net 5.0 and Syncfusion packages to v19.1. Kindly give it a try. And share with me a full stack trace of the exception or any information you might find useful to check this at my end.
Thanks for the tutorial. I would love if you can lead me on how to do the same with multiple related tables.
Thanks.
For showing values from a related table, you could use complex data binding or foreign key column support.
Complex data binding – We can use this when the relation table details are present as a part of the model as navigation properties. For more information refer to the user guide.
https://blazor.syncfusion.com/documentation/datagrid/columns/#complex-data-binding
Foreign key column – Use a foreign key column when there is no model level relation between the tables. For more information refer to the user guide.
https://blazor.syncfusion.com/documentation/datagrid/columns/#foreign-key-column
https://blazor.syncfusion.com/demos/datagrid/foreign-key-column?theme=bootstrap4
Edit and delete button is not Enabled. Why is that?
Thanks for the update. When the grid contains no rows then the Edit and Delete icons will be in disable state. This is the expected behavior. Are you referring to another issue? If so please share some information to reproduce this at my end.
Dear Madhu,
Very Nice tutorial/sample to dwell into blazor web assembly. Anticipating more and more samples from you. God bless you.
If I use Sfgrid Tvalue then I can to the CRUD operation but Filtering / Sorting doesn’t work. I go through
some articles and understand that datasource and Tvalue can not be put together. Could you please
provide one sample with CRUD operationg along with Filtering and Sorting. I would really appreciate.
Best Regards
In the Github sample, I didn’t handle filtering, sorting, and other data operation which is the reason you are facing this problem.
https://github.com/SyncfusionExamples/blazor-wasm-datagrid-efcore-crud/blob/main/LibraryManagement/Server/Controllers/BooksController.cs#L21
I will update the sample soon to include data operations too.
I’ve copied the code in your example and am getting the following error message:
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: This operation is only valid on generic types.
System.InvalidOperationException: This operation is only valid on generic types.
at System.RuntimeType.GetGenericTypeDefinition () in :0
at Syncfusion.Blazor.Grids.SfGrid`1[TValue].IsObservableCollection (System.Object data) in :0
at Syncfusion.Blazor.Grids.Internal.GridContent`1[TContent].OnParametersSet () in :0
at Microsoft.AspNetCore.Components.ComponentBase.CallOnParametersSetAsync () in :0
at Microsoft.AspNetCore.Components.ComponentBase.SetParametersAsync (Microsoft.AspNetCore.Components.ParameterView parameters) in :0
at Microsoft.AspNetCore.Components.Rendering.ComponentState.SetDirectParameters (Microsoft.AspNetCore.Components.ParameterView parameters) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.UpdateRetainedChildComponent (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldComponentIndex, System.Int32 newComponentIndex) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldFrameIndex, System.Int32 newFrameIndex) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldStartIndex, System.Int32 oldEndIndexExcl, System.Int32 newStartIndex, System.Int32 newEndIndexExcl) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldFrameIndex, System.Int32 newFrameIndex) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldStartIndex, System.Int32 oldEndIndexExcl, System.Int32 newStartIndex, System.Int32 newEndIndexExcl) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldFrameIndex, System.Int32 newFrameIndex) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldStartIndex, System.Int32 oldEndIndexExcl, System.Int32 newStartIndex, System.Int32 newEndIndexExcl) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForFramesWithSameSequence (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldFrameIndex, System.Int32 newFrameIndex) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.AppendDiffEntriesForRange (Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder+DiffContext& diffContext, System.Int32 oldStartIndex, System.Int32 oldEndIndexExcl, System.Int32 newStartIndex, System.Int32 newEndIndexExcl) in :0
at Microsoft.AspNetCore.Components.RenderTree.RenderTreeDiffBuilder.ComputeDiff (Microsoft.AspNetCore.Components.RenderTree.Renderer renderer, Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, System.Int32 componentId, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] oldTree, Microsoft.AspNetCore.Components.RenderTree.ArrayRange`1[T] newTree) in :0
at Microsoft.AspNetCore.Components.Rendering.ComponentState.RenderIntoBatch (Microsoft.AspNetCore.Components.Rendering.RenderBatchBuilder batchBuilder, Microsoft.AspNetCore.Components.RenderFragment renderFragment) in :0
at Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderInExistingBatch (Microsoft.AspNetCore.Components.Rendering.RenderQueueEntry renderQueueEntry) in :0
at Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessRenderQueue () in :0 blazor.webassembly.js:1:38061
Any ideas?
I was able to see this exception when the HTTP request to the given remote service returns 404 Not found error. I suspect that you are using the same remote service URL given in the GitHub sample which is not available in your application. Could you please give it a try by pointing out the proper remote service URL.
Hi,
Nice Tutorial , It’s work fine in Development Mode , but When I Deploy to IIS , it’s get error
Pleeeeeseee help me
blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: ‘<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
System.Text.Json.JsonException: ' System.Text.Json.JsonReaderException: ‘<' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
at System.Text.Json.Utf8JsonReader.Read()
at System.Text.Json.Serialization.JsonConverter`1[[testwebasse.Shared.Mobnew[], testwebasse.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
— End of inner exception stack trace —
at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex)
at System.Text.Json.Serialization.JsonConverter`1[[testwebasse.Shared.Mobnew[], testwebasse.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[Mobnew[]](JsonConverter jsonConverter, Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore[Mobnew[]](JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& state, JsonConverter converterBase)
at System.Text.Json.JsonSerializer.d__20`1[[testwebasse.Shared.Mobnew[], testwebasse.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
at System.Net.Http.Json.HttpContentJsonExtensions.d__3`1[[testwebasse.Shared.Mobnew[], testwebasse.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
at System.Net.Http.Json.HttpClientJsonExtensions.d__9`1[[testwebasse.Shared.Mobnew[], testwebasse.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
at testwebasse.Client.Pages.CugData.OnInitializedAsync()
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task )
Hi Dhiren,
Please check your Url value for SfDataManager in your razor component where you are trying to display the data.
Basically, your controller name which you are passing should exists
For example:
“/api/Data” – is Url Value. Similarly check yours.
Further, if SfDataManager control doesn’t get the data from passed URL(which would be null I believe) or path is invalid, this error will occur.
Hope this would resolve your issue.
Hi Dhiren,
We have tried to reproduce the reported issue by hosting the sample prepared using the blog using the steps mentioned in this blog (https://www.syncfusion.com/faq/blazor/host-and-deploy/how-do-i-deploy-a-blazor-application-in-iis). Unfortunately we are not able reproduce the issue. could you please share more details (like code example, datasource details) about the issue you are facing which will be very helpful us to analyze the issue further at our end.
@Yash – thanks for your suggestion.
Regards,
Vignesh Natarajan
Hi , I am getting this error and SfDataManager control doesn’t get the data from passed URL.
BooksController is my controller name which is under server->controllers-> folder
I have given api/Books as DataManager url but server responds with 404
:5001/api/Books:1 Failed to load resource: the server responded with a status of 404 ()
Hi Rajeshkannah,
We checked this from our side, unfortunately we could not reproduce the problem when binding data to Grid from WebApi service using WebApiAdaptor. Could you please share with us the following details about the issue, which would be helpful for us to look into this reported query.
1. Code example or a simple issue reproducing sample.
2. Screenshot of the Network tab response.
3. Syncfusion version details you are using.
4. Details of any exception/error occurred in browser console.
5. Bind OnActionFailure (https://blazor.syncfusion.com/documentation/datagrid/events#onactionfailure) event to grid, and share the details you get in the args of this event handler.
Regards,
Maithiliy K
Was doing fine until I got to the part that said:
Now the DbContext must be configured using a connection string and registered as a scoped service using the AddDbContext method in Startup.cs.
Can you give instructions for .NET 6 as well as .NET 5 please?
Hi Brian,
We suspect that you are facing struggle in implementing the below part in .Net6.
Now the DbContext must be configured using a connection string and registered as a scoped service using the AddDbContext method in Startup.cs.
For .Net6 we suggest you to implement the following changes in program.cs instead of startup.cs
Also please refer the below documentation for additional information in which we have mentioned changes for both .Net6/.Net5 for server application.
Reference: https://blazor.syncfusion.com/documentation/common/data-binding/bind-entity-framework#register-the-service-in-startupcs
Regards,
Maithiliy K
Comments are closed.