您需要在Blazor应用程序上了解的所有知识,并使用VS 2019,.NET Core 3和Web API创建ASP.NET Core Blazor CRUD应用程序

介绍 (Introduction)

In this article, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Visual Studio 2019, .NET Core 3, Entity Framework and Web API. Blazor is a new framework introduced by Microsoft.

在本文中,我们将看到如何使用Visual Studio 2019,.NET Core 3,实体框架和Web API为ASP.NET Core Blazor创建简单的CRUD应用程序。 Blazor是Microsoft引入的新框架。

Image 1

In this article, we will see how to create a simple CRUD application for ASP.NET Core Blazor using Visual Studio 2019, .NET Core 3, Entity Framework and Web API. Blazor is a new framework introduced by Microsoft.

在本文中,我们将看到如何使用Visual Studio 2019,.NET Core 3,实体框架和Web API为ASP.NET Core Blazor创建简单的CRUD应用程序。 Blazor是Microsoft引入的新框架。

Blazor:

西装外套:

Blazor has two kind of Application development on is Blazor Client app which is in preview now and also Blazor Server app. Blazor Client app runs in WebAssembly, Blazor Server app runs using SignalR. Blazor apps can be created using C#, Razor, and HTML instead of JavaScript Blazor WebAssembly Works in all modern web browsers also in mobile browsers. The main advantage we have in Blazor is C# code files and Razor files are compiled into .NET assemblies. Blazor has reusable components, Blazor Component can be as a page,Dialog or Entry Form, Blazor also used to create Single Page Applications. Blazor is used to create two kind of applications one is Blazor Client-Side App and another one is Blazor Server Side APP.here we will see some more details on   

Blazor正在进行两种应用程序开发,即正在预览的Blazor Client应用程序和Blazor Server应用程序。 Blazor Client应用程序在WebAssembly中运行,Blazor Server应用程序使用SignalR运行。 可以使用C#,Razor和HTML代替JavaScript创建Blazor应用程序,而在所有现代Web浏览器中以及移动浏览器中都可以使用JavaScript Blazor WebAssembly Works。 Blazor的主要优点是C#代码文件和Razor文件被编译为.NET程序集。 Blazor具有可重用的组件,Blazor组件可以作为页面,对话框或输入表单,Blazor也可用于创建单页应用程序。 Blazor用于创建两种应用程序,一种是Blazor客户端应用程序,另一种是Blazor服务器端应用程序。在这里,我们将看到有关以下内容的更多详细信息

Blazor Client App:

Blazor客户端应用程序:

  • Blazor Client Side is still in preview. 

    Blazor客户端仍处于预览状态。
  • Blazor Client side uses Web Assembly

    Blazor客户端使用Web Assembly
  • In Blazor Client Side all the.Net dll’s will be downloaded to browser. The download size might be bigger and might be some time delay in loading due to all downloads happen in client browser.

    在Blazor客户端,所有.Net dll都将下载到浏览器。 由于所有下载都在客户端浏览器中进行,因此下载大小可能会更大,并且可能会加载一些时间。
  • No need of server-side dependency for the Blazor Client-side application.

    Blazor客户端应用程序不需要服务器端依赖性。
  • All similer kind of JavaScript coding can be done in Blazor Client app and it’s not really needed to use of  JavaScript Interop.

    所有类似JavaScript编码都可以在Blazor Client应用中完成,而实际上不需要使用JavaScript Interop。
  • It can be deployed as Static site which means it support offline as well.

    可以将其部署为静态站点,这意味着它也支持脱机。
  • Debugging is more complicated than Blazor Server side.

    调试比Blazor Server端更复杂。
  • In client side leaking of database connectivity and also all the application code will be in client side and security level is not much good.

    在客户端泄漏数据库连接性以及所有应用程序代码都将在客户端泄漏,并且安全级别不是很好。

Blazor Server App:

Blazor服务器应用程序:

  • All the Component Process will be happening in the Server.

    所有组件过程都将在服务器中发生。
  • Blazor Server uses SignlR Connection to connect from the web server to browsers.

    Blazor Server使用SignlR Connection从Web服务器连接到浏览器。
  • In client side leaking of database connectivity is not happen as all will be happen in Server.

    在客户端,不会发生数据库连接泄漏,因为所有情况都将在Server中发生。
  • All the form connection will be happening in the server side and no dll’s download to the client side.As all the dll’s will be in web server.

    所有形式的连接都将在服务器端进行,并且没有dll下载到客户端。因为所有dll都将在Web服务器中。
  • Small download size and faster loading time than the Blazor Client App.

    与Blazor客户端应用程序相比,下载大小较小且加载时间更快。
  • We can use .Net core in Blazor server side.

    我们可以在Blazor服务器端使用.Net核心。
  • Debugging is great in Blazor Server Side.

    Blazor服务器端的调试非常棒。
  • Runs in any web browser as no need of WebAssemble.

    无需WebAssemble,即可在任何Web浏览器中运行。
  • Each browser session is open with SignalR connection.

    每个浏览器会话均通过SignalR连接打开。

背景 (Background)

Prerequisites

先决条件

使用代码 (Using the code)

Step 1 - Create a database and a table

第1步-创建数据库和表

We will be using our SQL Server database for our WEB API and EF. First, we create a database named CustDB and a table as CustDB. Here is the SQL script to create a database table and sample record insert query in our table. Run the query given below in your local SQL Server to create a database and a table to be used in our project. 

我们将使用WEB API和EFSQL Server数据库。 首先,我们创建一个名为CustDB的数据库和一个名为CustDB的表。 这是用于创建数据库表和示例记录插入查询SQL脚本。 在本地SQL Server中运行下面给出的查询,以创建要在我们的项目中使用的数据库和表。

USE MASTER       
GO       
       
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB       
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'CustDB' )       
DROP DATABASE CustDB       
GO       
       
CREATE DATABASE CustDB       
GO       
       
USE CustDB       
GO       
       
       
-- 1)  Customer Masters    

IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'CustomerMaster' )       
DROP TABLE CustomerMaster       
GO       
       
CREATE TABLE [dbo].[CustomerMaster](       
        [CustCd] [varchar](20) NOT NULL ,         
        [CustName] [varchar](100) NOT NULL,          
        [Email]  [nvarchar](100) NOT NULL,        
        [PhoneNo] [varchar](100) NOT NULL,           
        [InsertBy] [varchar](100) NOT NULL,   
        PRIMARY KEY (CustCd)  
)       
       
-- insert sample data to Student Master table       
INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C001','ACompany','acompany@gmail.com','01000007860','Shanun')       
       
INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C002','BCompany','bcompany@gmail.com','0100000001','Afraz')  

INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C003','CCompany','ccompany@gmail.com','01000000002','Afreen')  

INSERT INTO [CustomerMaster]   (CustCd,CustName,Email,PhoneNo,InsertBy)       
     VALUES ('C004','DCompany','dcompany@gmail.com','01000001004','Asha')  
            
     select * from CustomerMaster 

Step 2 - Create ASP.NET Core Blazor Server Application

第2步-创建ASP.NET Core Blazor服务器应用程序

After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2019 >> Visual Studio 2019 on your desktop. Click New >> Project. 

安装了上面列出的所有必备组件后,在桌面上单击开始>>程序>> Visual Studio 2019 >> Visual Studio 2019。 单击新建>>项目。

Image 2

Select Blazor App and click Next button.

选择Blazor App,然后单击下一步按钮。

Image 3

Select your project folder and Enter your Project name and then click Create button.

选择您的项目文件夹并输入您的项目名称,然后单击创建按钮。

Image 4

Select Blazor Server App

选择Blazor服务器应用程序

Image 5

After creating ASP.NET Core Blazor Server Application, wait for a few seconds. You will see the below structure in solution explorer.

创建ASP.NET Core Blazor服务器应用程序后,请等待几秒钟。 您将在解决方案资源管理器中看到以下结构。

Image 6

In the Data folder we can add all our Model, DBContext Class, Services and Controller, we will see that in this article.

Data文件夹中,我们可以添加所有模型,DBContext类,服务和控制器,我们将在本文中看到。

In the Pages folder we can add all our component files.component file all should have the .razor extension with the file name.

在Pages文件夹中,我们可以添加所有组件文件.component文件都应具有.razor扩展名并带有文件名。

In the Shared folder we can add all left menu form NavMenu.razor file and change the main content from the MainLayout.razor file.

在Shared文件夹中,我们可以添加所有左侧菜单形式的NavMenu.razor文件,并从MainLayout.razor文件中更改主要内容。

In the _Imports.razor file we can see all set of imports has been added inorder to used in all component pages.

在_Imports.razor文件中,我们可以看到已添加所有导入集,以便在所有组件页面中使用。

In the App.razor file we will add our main component to be displayed by default when run in browser.Appsertings.json can be used to add the connection string.

在App.razor文件中,我们将添加要在浏览器中运行时默认显示的主要组件.Appsertings.json可用于添加连接字符串。

Startup.cs file is important file where we add all our endpoints example like Controller end points, HTTP Client,add services and dbcontext to be used in startup Configuration method.

Startup.cs文件是重要文件,我们在其中添加了所有端点示例(如控制器端点,HTTP客户端,添加服务和dbcontext),以在启动Configuration方法中使用。

Run to test the application

运行以测试应用程序

When we run the application, we can see that the left side has navigation and the right side contains the data. We can see as the default sample pages and menus will be displayed in our Blazor web site. We can use the pages or remove it and start with our own page.

运行应用程序时,我们可以看到左侧具有导航功能,右侧包含数据。 我们可以看到默认示例页面和菜单将显示在Blazor网站上。 我们可以使用页面或将其删除,然后从我们自己的页面开始。

Image 7

Debug in component

调试组件

  The big advantage of Blazor is as we can use our C# code in razor and also keep the break point in the code part and in browser we can debug and check for all our business logic is working properly and to trace any kind error easily with break point.

Blazor的最大优势在于,我们可以在剃刀中使用C#代码,并将断点保留在代码部分中,而在浏览器中,我们可以调试和检查我们所有的业务逻辑是否正常工作,并轻松找到带有break的任何类型的错误点。

For this we take our existing Counter component page.

为此,我们使用现有的“计数器”组件页面。

This is the actual code of our Counter page as in the counter we can see there is button and in button click called the method to perform the increment.

这是“计数器”页面的实际代码,因为在计数器中我们可以看到有一个按钮,在按钮中单击称为执行增量的方法。

Image 8

We add one more button and in button click event we call the method and bind the name in our component page.  In html design part we add the below code.

我们再添加一个按钮,并在按钮单击事件中调用方法并在组件页面中绑定名称。 在html设计部分,我们添加以下代码。

<h1>My Blozor Code part</h1>
    My Name is : @myName   <br />
 <button @onclick="ClickMe">Click Me</button>

Note that : all the C# code part and functions can be written under the  @code {} part. We add the method ClickMe and declare property to bind the name inside the @Code part

请注意:所有C#代码部分和函数都可以在@code {}部分下编写。 我们添加方法ClickMe并声明属性以将名称绑定到@Code部分中

[Parameter]
    public string myName { get; set; }
private void ClickMe()
    {
        myName="Shanu";
    }

The complete Coutner Component page code will be like this.

完整的Coutner Component页面代码将像这样。

Image 9 Now lets add the break point in our ClickMe method

Image 10

Run the program and open the counter page.

运行程序并打开计数器页面。

Image 11
Image 13

图片12

We can see as when we click on the Click Me button we can debug and check for the value from the breakpoint we placed.

我们可以看到,当单击“单击我”按钮时,我们可以调试并从放置的断点检查值。

Now lets see on performing CRUD operation using EF and Web API in Bloazor.

现在让我们看看如何在Bloazor中使用EF和Web API执行CRUD操作。

Step 3 - Using Entity Framework

步骤3-使用实体框架

To use the Entity Framework in our Blazor application we need to install the below packages

要在Blazor应用程序中使用实体框架,我们需要安装以下软件包

Install the Packages

安装软件包

Microsoft.EntityFrameworkCore.SqlServer  - For using EF and SQL Server

Microsoft.EntityFrameworkCore.SqlServer-用于使用EF和SQL Server

Microsoft.EntityFrameworkCore.Tools  - For using EF and SQL Server

Microsoft.EntityFrameworkCore.Tools-用于使用EF和SQL Server

Microsoft.AspNetCore.Blazor.HTTTPClient -  For communicating WEB API from our Blazor Component.

Microsoft.AspNetCore.Blazor.HTTTPClient-用于从我们的Blazor组件传递WEB API。

First we will add the Microsoft.EntityFrameworkCore.SqlServer  ,For this right click on the project and click on Manage NuGet Packages.

首先,我们将添加Microsoft.EntityFrameworkCore.SqlServer,为此右键单击项目,然后单击“管理NuGet包”。

Image 14

Search for all the three packages and install all the needed packages like below image.

搜索所有三个软件包并安装所有需要的软件包,如下图所示。

Add DB Connection string

添加数据库连接字符串

Open the appsetting file and add the connection string like below image.

打开appsetting文件,然后添加连接字符串,如下图所示。

"ConnectionStrings": {

    "DefaultConnection": "Server= DBServerName;Database=CustDB;user id= SQLID;-password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true"

},

Image 15

Create Model Class

创建模型类

Next, we need to create the Model class with same as our SQL Table name and also define the property fields similar to our SQL filed name as below.

接下来,我们需要使用与SQL Table名称相同的名称来创建Model类,并定义类似于我们SQL字段名称的属性字段,如下所示。

Right Click the Data Folder and create new class file as “CustomerMaster.cs”

右键单击数据文件夹,然后将新类文件创建为“ CustomerMaster.cs”

Image 16

In the class we add the property field name same as our table column names like below code.

在该类中,我们添加与表列名称相同的属性字段名称,如以下代码所示。

[Key]
  public string CustCd { get; set; }
  public string CustName { get; set; }
  public string Email { get; set; }
  public string PhoneNo { get; set; }
 public string InsertBy { get; set; }


Create dbConext Class

创建dbConext类

Next, we need to create the dbContext class.Right Click the Data Folder and create new class file as “SqlDbContext.cs”

接下来,我们需要创建dbContext类。右键单击“数据文件夹”,然后将新的类文件创建为“ SqlDbContext.cs”

Image 17

We add the below code in the DbContext class as below in order to add the SQLContext and add the DBset for our CustomerMaster Model.

如下所示,我们在DbContext类中添加以下代码,以便添加SQLContext并为CustomerMaster模型添加DBset。

public class SqlDbContext:DbContext
  {
      public SqlDbContext(DbContextOptions<SqlDbContext> options)
         : base(options)
      {
      }
      public DbSet<BlazorCrudA1.Data.CustomerMaster> CustomerMaster { get; set; }
  }


Adding DbContext in Startup

在启动中添加DbContext

Adding the DbContext in Startup.cs file ConfigureServices method as below code and also we give the connection string which we used to connect to SQLServer and DB.

在Startup.cs文件的ConfigureServices方法中添加DbContext,如下代码,并且我们还提供了用于连接到SQLServer和DB的连接字符串。

services.AddDbContext<SqlDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

Note that in the ConfigureServices method we can also see as the weatherforecast service has been added.if we create an new service then we need to add the service in like below code in  ConfigureServices method.

请注意,在ConfigureServices方法中我们还可以看到已添加了weatherforecast服务。如果我们创建了一个新服务,则需要在ConfigureServices方法中以下面的代码添加该服务。

services.AddSingleton<WeatherForecastService>();


Creating Web API for CRUD operation

创建用于CRUD操作的Web API

To create our WEB API Controller, right-click Controllers folder. Click Add New Controller.

要创建我们的WEB API控制器,请右键单击Controllers文件夹。 单击添加新控制器。

Here we will be using Scaffold method to create our WEB API. We select API Controller with actions, using Entity Framework and click Add button.

在这里,我们将使用Scaffold方法创建我们的WEB API。 我们使用Entity Framework选择带有操作的API Controller,然后单击“添加”按钮。

Image 18

Select our Model  class and DBContext class and click Add button.

选择我们的Model类和DBContext类,然后单击Add按钮。

Image 19

Our WEB API with Get/Post/Put and Delete method for performing the CRUD operation will be automatically created and we no need to write any code in Web API now as we have used the Scaffold method for all the actions and methods add with code.

我们将自动创建带有用于执行CRUD操作的带有Get / Post / Put和Delete方法的WEB API,并且由于我们已经使用了Scaffold方法进行所有操作,并且添加了代码的方法,因此现在无需在Web API中编写任何代码。

Image 20

To test Get Method, we can run our project and copy the GET method API path. Here, we can see our API path to get /api/CustomerMasters/ Run the program and paste API path to test our output.

为了测试Get Method,我们可以运行我们的项目并复制GET method API路径。 在这里,我们可以看到获取/ api / CustomerMasters /的API路径。运行该程序并粘贴API路径以测试我们的输出。

Image 21

If you see this error means then we need to add the endpoints of controller in the Startup.cs  file Configure method. Add the below code in the Configure method in Startup.cs file

如果您看到此错误,则我们需要在Startup.cs文件的Configure方法中添加控制器的端点。 在Startup.cs文件的Configure方法中添加以下代码

endpoints.MapControllers();

we add inside the UseEndpoints like below code in Configure method.

我们在Configure方法中的UseEndpoints之内添加如下代码。

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });

Now run again and check for /api/CustomerMasters/ to see the Json data from our database.

Image 22

现在再次运行并检查/ api / CustomerMasters /以查看数据库中的Json数据。

Now we will bind all this WEB API Json result in component.

现在,我们将所有这些WEB API Json结果绑定到组件中。

Working with Client Project

处理客户项目

First, we need to add the Razor Component page

首先,我们需要添加“剃刀组件”页面

Add Razor Component

添加剃刀组件

To add the Razor Component page right click the Pages folder from the Client project. Click on Add >> New Item >> Select Razor Component >> Enter your component name,Here we have given the name as Customerentry.razor

要添加“剃刀组件”页面,请在“客户端”项目中右键单击“页面”文件夹。 单击添加>>新建项目>>选择剃刀组件>>输入您的组件名称,此处我们将其命名为Customerentry.razor

Note all the component file need to have the extentions as .razor.

注意,所有组件文件都必须具有扩展名“ .razor”。

Image 23

In Razor Component Page we have 3 parts of code as first is the Import part where we import all the references and models for using in the component, HTML design and data bind part and finally we have the function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in Component page.

在Razor Component Page中,我们有3部分代码,首先是Import部分,在其中我们导入要在组件中使用的所有引用和模型,HTML设计和数据绑定部分,最后是函数部分,以调用所有Web API来绑定到我们HTML页面中,并执行要在“组件”页面中显示的客户端业务逻辑。

Import part

进口零件

First, we import all the needed support files and references in our Razor View page. Here we have first imported our Model class to be used in our view and also imported HTTPClient for calling the Web API to perform the CRUD operations.

首先,我们在Razor View页面中导入所有必需的支持文件和参考。 在这里,我们首先导入了要在视图中使用的Model类,还导入了HTTPClient来调用Web API来执行CRUD操作。

@page "/customerentry"
@using BlazorCrudA1.Data
@using System.Net.Http
@inject HttpClient Http 
@using Microsoft.Extensions.Logging

Register HTTPClient for Server side Blazor

为服务器端Blazor注册HTTPClient

In order to use the HTTPClient in Blazor Server side we need to add the below code in Startup.cs ConfigureServices method.

为了在Blazor服务器端使用HTTPClient,我们需要在Startup.cs ConfigureServices方法中添加以下代码。

services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });

            // Server Side Blazor doesn't register HttpClient by default
            if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
            {
                // Setup HttpClient for server side in a client side compatible fashion
                services.AddScoped<HttpClient>(s =>
                {
                    // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.      
                    var uriHelper = s.GetRequiredService<NavigationManager>();
                    return new HttpClient
                    {
                        BaseAddress = new Uri(uriHelper.BaseUri)
                    };
                });
            }

HTML design and data Bind part

HTML设计和数据绑定部分

Next, we design our Customer Master details page to display the Customer details from the database and created a form to Insert and update the Customer details we also have Delete button to delete the Custoemr records from the database.

接下来,我们设计“客户主数据”页面以显示数据库中的“客户”详细信息,并创建一个表单以插入和更新“客户”详细信息,我们还具有“删除”按钮以从数据库中删除Custoemr记录。

For binding in Blazor we use the @bind="@custObj.CustCd"  and to call the method using @onclick="@AddNewCustomer"

对于Blazor中的绑定,我们使用@ bind ="@custObj.CustCd"并使用@ onclick ="@AddNewCustomer"调用该方法

<h1> ASP.NET Core BLAZOR CRUD demo for Customers</h1>
<hr />
<table width="100%" style="background:#05163D;color:honeydew">
    <tr>
        <td width="20"> </td>
        <td>
            <h2> Add New Customer Details</h2>
        </td>
        <td> </td>
        <td align="right">
            <button class="btn btn-info" @onclick="@AddNewCustomer">Add New Customer</button>
        </td>
        <td width="10"> </td>
    </tr>
    <tr>
        <td colspan="2"></td>
    </tr>
</table>
<hr />
@if (showAddrow == true)
{
    <form>
        <table class="form-group">
            <tr>
                <td>
                    <label for="Name" class="control-label">Customer Code</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.CustCd" />
                </td>
                <td width="20"> </td>
                <td>
                    <label for="Name" class="control-label">Customer Name</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.CustName" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Email" class="control-label">Email</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.Email" />
                </td>
                <td width="20"> </td>
                <td>
                    <label for="Name" class="control-label">Phone</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.PhoneNo" />
                </td>
            </tr>
            <tr>
                <td>
                    <label for="Name" class="control-label">Insert By</label>
                </td>
                <td>
                    <input type="text" class="form-control" @bind="@custObj.InsertBy" />
                </td>
                <td width="20"> </td>
                <td>
                </td>
                <td>
                    <button type="submit" class="btn btn-success" @onclick="@AddCustomer" style="width:220px;">Save</button>
                </td>
            </tr>
        </table>
    </form>
}
<table width="100%" style="background:#0A2464;color:honeydew">
    <tr>
        <td width="20"> </td>
        <td>
            <h2>Customer List</h2>
        </td>

    </tr>
    <tr>
        <td colspan="2"></td>
    </tr>
</table> 

@if (custs == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Customer Code</th>
                <th>Customerr Name</th>
                <th>Email</th>
                <th>Phone</th>
                <th>Inserted By</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var cust in custs)
            {
                <tr>
                    <td>@cust.CustCd</td>
                    <td>@cust.CustName</td>
                    <td>@cust.Email</td>
                    <td>@cust.PhoneNo</td>
                    <td>@cust.InsertBy</td>
                    <td><button class="btn btn-primary" @onclick="@(async () => await EditCustomer(cust.CustCd))" style="width:110px;">Edit</button></td>

                    <td><button class="btn btn-danger" @onclick="@(async () => await DeleteCustomer(cust.CustCd))">Delete</button></td>
                </tr>

            }
        </tbody>
    </table>
}

Function Part

功能部分

Function part to call all the web API to bind in our HTML page and also to perform client-side business logic to be displayed in Component page.In this Function we create a separate function for Add, Edit and Delete the student details and call the Web API Get,Post,Put and Delete method to perform the CRUD operations and in HTML we call all the function and bind the results.

该函数部分调用所有Web API来绑定到我们HTML页面中,并执行要在组件页面中显示的客户端业务逻辑。在此函数中,我们创建了一个单独的函数来添加,编辑和删除学生详细信息,并调用Web API的Get,Post,Put和Delete方法执行CRUD操作,在HTML中,我们调用所有函数并绑定结果。

@code {

    private CustomerMaster[] custs;

    CustomerMaster custObj = new CustomerMaster();

    string ids = "0";
    bool showAddrow = false;

    bool loadFailed;

    protected override async Task OnInitializedAsync()
    {
        ids = "0";
        custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
    }

    void AddNewCustomer()
    {
        ids = "0";
        showAddrow = true;
        custObj = new CustomerMaster();
    }
    // Add New Customer Details Method
    protected async Task AddCustomer()
    {
        if (ids == "0")

        {
            await Http.SendJsonAsync(HttpMethod.Post, "/api/CustomerMasters/", custObj);
            custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
        }
        else
        {
            await Http.SendJsonAsync(HttpMethod.Put, "/api/CustomerMasters/" + custObj.CustCd, custObj);
            custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
        }

        showAddrow = false;
    }
    // Edit Method
    protected async Task EditCustomer(string CustomerID)
    {
        showAddrow = true;

        ids = "1";
        //try
        //{
        loadFailed = false;
        ids = CustomerID.ToString();
        custObj = await Http.GetJsonAsync<CustomerMaster>("/api/CustomerMasters/" + CustomerID);

        string s = custObj.CustCd;

        showAddrow = true;

        //    }
        //catch (Exception ex)
        //{
        //    loadFailed = true;
        //    Logger.LogWarning(ex, "Failed to load product {ProductId}", CustomerID);
        //}
    }
    // Delte Method
    protected async Task DeleteCustomer(string CustomerID)
    {
        showAddrow = false;

        ids = CustomerID.ToString();
        await Http.DeleteAsync("/api/CustomerMasters/" + CustomerID);

        custs = await Http.GetJsonAsync<CustomerMaster[]>("/api/CustomerMasters/");
    }

}

Navigation Menu

导航菜单

Now we need to add this newly added CustomerEntry Razor component to our left Navigation. For adding this Open the Shared Folder and open the NavMenu.cshtml page and add the menu.

现在,我们需要将此新添加的CustomerEntry Razor组件添加到左侧导航中。 要添加此内容,请打开“共享文件夹”,然后打开NavMenu.cshtml页面并添加菜单。

<li class="nav-item px-3">
            <NavLink class="nav-link" href="CustomerEntry">
                <span class="oi oi-list-rich" aria-hidden="true"></span> Customer Master
            </NavLink>
        </li>

Build and Run the application

生成并运行应用程序

Image 24

兴趣点 (Points of Interest)

Note that when creating the DBContext and setting the connection string, don’t forget to add your SQL connection string. Here we have created table in SQl server and used with Web API you can also do this with Services and also Code First approach, Hope you all like this article. In the next article, we will see more examples to work with Blazor. It's really very cool and awesome to work with Blazor.

请注意,在创建DBContext并设置连接字符串时,请不要忘记添加SQL连接字符串。 在这里,我们已经在SQl服务器中创建了表,并与Web API一起使用,您也可以通过Services以及Code First方法进行此操作,希望大家都喜欢本文。 在下一篇文章中,我们将看到更多与Blazor一起使用的示例。 与Blazor一起工作真的非常酷,而且很棒。

翻译自: https://www.codeproject.com/Articles/5253709/All-you-need-to-know-on-Blazor-app-and-create-ASP

参与评论 您还未登录,请先 登录 后发表或查看评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:编程工作室 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值