mongodb 命令执行_如何使用Blazor和MongoDB执行CRUD操作

mongodb 命令执行

介绍 (Introduction)

In this article, we will create a Blazor application using MongoDB as our database provider. We will create a Single Page Application (SPA) and perform CRUD operations on it. A modal popup will display the form to handle the user inputs. The form also has a dropdown list, which will bind to a DB collection.

在本文中,我们将使用MongoDB作为我们的数据库提供程序来创建Blazor应用程序。 我们将创建一个单页应用程序(SPA)并对其执行CRUD操作。 模态弹出窗口将显示该表单以处理用户输入。 该表单还具有一个下拉列表,该列表将绑定到数据库集合。

We will use Visual Studio 2017 and MongoDB 4.0.

我们将使用Visual Studio 2017和MongoDB 4.0。

Take a look at the final application.

看一下最终的应用程序。

先决条件 (Prerequisites)

  • Install the .NET Core 2.1 or above SDK from here

    此处安装.NET Core 2.1或更高版本的SDK

  • Install Visual Studio 2017 v15.7 or above from here

    此处安装Visual Studio 2017 v15.7或更高版本

  • Install ASP.NET Core Blazor Language Services extension from here

    此处安装ASP.NET Core Blazor语言服务扩展

  • Download and install MongoDB community edition. You can find the installation guide here.

    下载并安装MongoDB社区版。 您可以在此处找到安装指南。

Visual Studio 2017 versions below v15.7 do not support Blazor framework.

v15.7以下的Visual Studio 2017版本不支持Blazor框架。

源代码 (Source Code)

Get the source code from GitHub.

GitHub获取源代码。

配置MongoDB (Configuring MongoDB)

After installing the MongoDB, we need to add the path of MongoDB binaries to the System PATH variable. The default installation path in a Windows machine is C:\Program Files\MongoDB. Hence you need to include C:\Program Files\MongoDB\Server\4.0\bin in the System PATH variable. If you are not using Windows then you can find the process of configuring the MongoDB binaries at the installation guide link provided in the prerequisites section above.

安装MongoDB之后,我们需要将MongoDB二进制文件的路径添加到System PATH变量中。 Windows机器中的默认安装路径是C:\Program Files\MongoDB 。 因此,您需要在System PATH变量中包含C:\Program Files\MongoDB\Server\4.0\bin 。 如果您未使用Windows,则可以在上面先决条件部分中提供的安装指南链接中找到配置MongoDB二进制文件的过程。

使用MongoDB (Working With MongoDB)

We need to set up the path where the data will be stored in our machine. Open the command prompt as administrator and run the following command to set the data storage path in your machine.

我们需要设置将数据存储在机器中的路径。 以管理员身份打开命令提示符,然后运行以下命令来设置计算机中的数据存储路径。

mongod --dbpath C:\MongoData

You can provide the path of any folder where you want to store the data. This command will connect to MongoDB on port 27017 (the default port for MongoDB connection). Refer to the image below:

您可以提供要在其中存储数据的任何文件夹的路径。 此命令将在端口27017(MongoDB连接的默认端口)上连接到MongoDB。 请参考下图:

Important Note:

重要的提示:

It is advisable to use the command prompt over PowerShell while executing MongoDB commands as all MongoDB commands do not work in PowerShell.

建议在执行MongoDB命令时在PowerShell上使用命令提示符,因为所有MongoDB命令在PowerShell中均不起作用。

Open a new command prompt window and execute the command mongo to start the mongo server. Refer to the image below.

打开一个新的命令提示符窗口,然后执行命令mongo以启动mongo服务器。 请参考下图。

Run the following command to create the database:

运行以下命令来创建数据库:

use EmployeeDB

This will create our database EmployeeDB. Execute the following command to create a new collection inside the database:

这将创建我们的数据库EmployeeDB 。 执行以下命令以在数据库内部创建一个新集合:

db.createCollection('EmployeeRecord')

This will create a collection EmployeeRecord in our database. MongoDB stores data in JSON-like documents. Let us insert a sample document in our EmployeeRecord collection. Run the following command.

这将在我们的数据库中创建一个EmployeeRecord集合。 MongoDB将数据存储在类似JSON的文档中。 让我们在EmployeeRecord集合中插入一个示例文档。 运行以下命令。

db.EmployeeRecord.insert({'Name':'Ankit','Gender':'Male','Department':'HR','City':'Mumbai'})

You can observe that we have provided the data in a JSON format as a key-value pair. Run the following command to list all the documents from the EmployeeRecord collection.

您可以观察到,我们以JSON格式提供了数据作为键值对。 运行以下命令以列出EmployeeRecord集合中的所有文档。

db.EmployeeRecord.find({})

The database schema will add _id property to each document in the collection. This property is of type ObjectId and it will be generated automatically. We will use this _id property to uniquely identify a document in the collection. Refer to the image below:

数据库模式将向集合中的每个文档添加_id属性。 此属性的类型为ObjectId,它将自动生成。 我们将使用此_id属性来唯一标识集合中的文档。 请参考下图:

If you want to remove all the documents from the EmployeeRecord collection then you need to run the following command:

如果要从EmployeeRecord集合中删除所有文档,则需要运行以下命令:

db.EmployeeRecord.remove({})

We will create another collection to store a list of city names which is used to populate the City field of EmployeeRecord collection. We will also bind this collection to a dropdown list in our web application from which the user will select the desired city.

我们将创建另一个集合来存储城市名称列表,该列表用于填充EmployeeRecord集合的“城市”字段。 我们还将将此集合绑定到Web应用程序中的下拉列表,用户将从中选择所需的城市。

Run the following command to create the Cities collection.

运行以下命令以创建Cities集合。

db.createCollection('Cities')

We will insert five sample city names in this collection. To insert the documents in bulk in the Cities collection, run the following command:

我们将在此集合中插入五个示例城市名称。 要将文档批量插入Cities集合中,请运行以下命令:

db.Cities.insertMany([   { CityName : "New Delhi" },   { CityName : "Mumbai"},   { CityName : "Hyderabad"},   { CityName : "Chennai"},   { CityName : "Bengaluru" }])

Refer to the image below:

请参考下图:

创建Blazor Web应用程序 (Create a Blazor Web Application)

Open Visual Studio and select File >> New >> Project.

打开Visual Studio,然后选择“文件>>新建>>项目”。

After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel. Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as BlazorWithMongo and press OK.

选择项目后,将打开“新建项目”对话框。 从左侧面板的Visual C#菜单中选择.NET Core。 然后,从可用的项目类型中选择“ ASP.NET Core Web应用程序”。 将项目名称命名为BlazorWithMongo ,然后按OK。

After clicking on OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select “Blazor (ASP .NET Core hosted)” template and press OK.

单击确定后,将打开一个新对话框,要求您选择项目模板。 您可以在模板窗口的左上方观察两个下拉菜单。 从这些下拉列表中选择“ .NET Core”和“ ASP.NET Core 2.0”。 然后,选择“ Blazor(ASP.NET Core托管)”模板,然后按OK。

Now, our Blazor solution will be created. You can observe that we have three project files created in this solution

现在,将创建我们的Blazor解决方案。 您可以看到我们在此解决方案中创建了三个项目文件

  1. BlazorWithMongo.Client — It has the client side code and contains the pages that will be rendered on the browser.

    BlazorWithMongo.Client —它具有客户端代码,并且包含将在浏览器中呈现的页面。
  2. BlazorWithMongo.Server — It has the server side codes such as data access layer and web API.

    BlazorWithMongo.Server —它具有服务器端代码,例如数据访问层和Web API。
  3. BlazorWithMongo.Shared — It contains the shared code that can be accessed by both client and server. It contains our Model class and DB context class.

    BlazorWithMongo.Shared —它包含可以由客户端和服务器访问的共享代码。 它包含我们的Model类和DB上下文类。

安装MongoDB驱动程序 (Installing MongoDB driver)

To access the MongoDB from our application we need to install the MongoDB driver using package manager console. We will install it in BlazorWithMongo.Shared project so that it can be accessible to Server project also.

要从我们的应用程序访问MongoDB,我们需要使用程序包管理器控制台安装MongoDB驱动程序。 我们将其安装在BlazorWithMongo.Shared项目中,以便Server项目也可以访问它。

Navigate to Tools >> NuGet Package Manager >> Package Manager Console. Select BlazorWithMongo.Shared from Default project drop-down and run the following command:

导航到工具>> NuGet软件包管理器>> Package Manager Cons ole. Select BlazorWith 从默认项目下拉列表中ole. Select BlazorWith Mongo.Shared并运行以下命令:

Install-Package MongoDB.Driver

Refer to the image below:

请参考下图:

创建模型 (Creating the Model)

We will create our model class in BlazorWithMongo.Shared project. Right click on BlazorWithMongo.Shared and select Add >> New Folder. Name the folder as Models. Again, right click on the Models folder and select Add >> Class to add a new class file. Put the name of your class as Employee.cs and click Add.

我们将在BlazorWithMongo.Shared项目中创建模型类。 右键单击BlazorWithMongo.Shared然后选择添加>>新建文件夹。 将该文件夹命名为Models。 再次右键单击Models文件夹,然后选择Add >> Class添加新的类文件。 将班级名称命名为Employee.cs,然后单击添加。

Open the Employee.cs class and put the following code into it.

打开Employee.cs类,并将以下代码放入其中。

using System;using System.Collections.Generic;using System.Text;using MongoDB.Bson;using MongoDB.Bson.Serialization.Attributes;namespace BlazorWithMongo.Shared.Models{    public class Employee    {        [BsonId]        [BsonRepresentation(BsonType.ObjectId)]        public string Id { get; set; }        public string Name { get; set; }        public string City { get; set; }        public string Department { get; set; }        public string Gender { get; set; }    }}

We have included the Id property of the type ObjectId in our class definition and decorated it with [BsonId] attribute. This property is required to map the model objects to the MongoDB collection.

我们已包含ID 类定义中ObjectId类型的属性,并使用[BsonId]属性对其进行[BsonId] 。 需要此属性才能将模型对象映射到MongoDB集合。

Similarly, create another class file Cities.cs and put the following code into it.

同样,创建另一个类文件Cities.cs并将以下代码放入其中。

using System;using System.Collections.Generic;using System.Text;using MongoDB.Bson;using MongoDB.Bson.Serialization.Attributes;namespace BlazorWithMongo.Shared.Models{    public class Cities    {        [BsonId]        [BsonRepresentation(BsonType.ObjectId)]        public string Id { get; set; }        public string CityName { get; set; }    }}

创建数据库上下文类 (Creating the DB context class)

Add a new class file to the Models folder and name it EmployeeDBContext.cs. Put the following code into it:

将一个新的类文件添加到Models文件夹中,并将其命名为EmployeeDBContext.cs 。 将以下代码放入其中:

using MongoDB.Driver;using System;using System.Collections.Generic;using System.Text;namespace BlazorWithMongo.Shared.Models{    public class EmployeeDBContext    {        private readonly IMongoDatabase _mongoDatabase;        public EmployeeDBContext()        {            var client = new MongoClient("mongodb://localhost:27017");            _mongoDatabase = client.GetDatabase("EmployeeDB");        }        public IMongoCollection<Employee> EmployeeRecord        {            get            {                return _mongoDatabase.GetCollection<Employee>("EmployeeRecord");            }        }        public IMongoCollection<Cities> CityRecord        {            get            {                return _mongoDatabase.GetCollection<Cities>("Cities");            }        }    }}

Here we have defined a MongoClient which will connect to the MongoDB server instance using the default connection string for MongoDB. We are using the GetDatabase method to fetch the database instance. The method EmployeeRecord is used to fetch the EmployeeRecord collection from our database and map it to the Employee model class. Similarly, the method CityRecord will fetch the Cities collection from the database and map it to the Cities model class.

在这里,我们定义了一个MongoClient ,它将使用MongoDB的默认连接字符串连接到MongoDB服务器实例。 我们正在使用GetDatabase方法来获取数据库实例。 方法EmployeeRecord用于从我们的数据库中获取EmployeeRecord集合并将其映射到Employee模型类。 同样,方法CityRecord将从数据库中获取Cities集合并将其映射到Cities模型类。

为应用程序创建数据访问层 (Creating Data Access Layer for the Application)

Right-click on BlazorWithMongo.Server project and then select Add >> New Folder and name the folder as DataAccess. We will be adding our class to handle database related operations inside this folder only.

右键单击BlazorWithMongo.Server项目,然后选择添加>>新建文件夹,并将文件夹命名为数据访问。 我们将添加我们的类以仅处理此文件夹内的数据库相关操作。

Right click on DataAccess folder and select Add >> Class. Name your class EmployeeDataAccessLayer.cs. Open EmployeeDataAccessLayer.cs and put the following code into it:

右键单击DataAccess文件夹,然后选择添加>>类。 命名class EmployeeDataAccessLa 你们 r.cs. Open EmployeeDataAccessLa yer.cs并将以下代码放入其中:

using BlazorWithMongo.Shared.Models;using MongoDB.Driver;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace BlazorWithMongo.Server.DataAccess{    public class EmployeeDataAccessLayer    {        EmployeeDBContext db = new EmployeeDBContext();        //To Get all employees details               public List<Employee> GetAllEmployees()        {            try            {                return db.EmployeeRecord.Find(_ => true).ToList();            }            catch            {                throw;            }        }        //To Add new employee record               public void AddEmployee(Employee employee)        {            try            {                db.EmployeeRecord.InsertOne(employee);            }            catch            {                throw;            }        }        //Get the details of a particular employee              public Employee GetEmployeeData(string id)        {            try            {                FilterDefinition<Employee> filterEmployeeData = Builders<Employee>.Filter.Eq("Id", id);                return db.EmployeeRecord.Find(filterEmployeeData).FirstOrDefault();            }            catch            {                throw;            }        }        //To Update the records of a particular employee              public void UpdateEmployee(Employee employee)        {            try            {                db.EmployeeRecord.ReplaceOne(filter: g => g.Id == employee.Id, replacement: employee);            }            catch            {                throw;            }        }        //To Delete the record of a particular employee              public void DeleteEmployee(string id)        {            try            {                FilterDefinition<Employee> employeeData = Builders<Employee>.Filter.Eq("Id", id);                db.EmployeeRecord.DeleteOne(employeeData);            }            catch            {                throw;            }        }        // To get the list of Cities          public List<Cities> GetCityData()        {            try            {                return db.CityRecord.Find(_ => true).ToList();            }            catch            {                throw;            }        }    }}

Here we have defined the methods to perform CRUD operations on the EmployeeDB database.

在这里,我们定义了对EmployeeDB数据库执行CRUD操作的方法。

将Web API控制器添加到应用程序 (Adding the web API Controller to the Application)

Right-click on BlazorWithMongo.Server/Controllers folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Web from the left panel, then select “API Controller Class” from the templates panel and put the name as EmployeeController.cs. Click Add.

右键单击BlazorWithMongo.Server/Controllers文件夹,然后选择添加>>新建项。 “添加新项”对话框将打开。 小号ELE CT左侧面板中的网络,然后从模板面板中选择“API控制器类”,并把呐me as EmployeeControl ler.cs. 单击添加。

This will create our API EmployeeController class. We will call the methods of EmployeeDataAccessLayer class to fetch data and pass on the data to the client side

这将创建我们的API EmployeeController类。 我们将调用EmployeeDataAccessLayer类的方法来获取数据并将数据传递给客户端

Open EmployeeController.cs file and put the following code into it:

打开EmployeeController.cs文件,并将以下代码放入其中:

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using BlazorWithMongo.Server.DataAccess;using BlazorWithMongo.Shared.Models;using Microsoft.AspNetCore.Mvc;namespace BlazorWithMongo.Server.Controllers{    public class EmployeeController : Controller    {        EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer();        [HttpGet]        [Route("api/Employee/Index")]        public IEnumerable<Employee> Index()        {            return objemployee.GetAllEmployees();        }        [HttpPost]        [Route("api/Employee/Create")]        public void Create([FromBody] Employee employee)        {            objemployee.AddEmployee(employee);        }        [HttpGet]        [Route("api/Employee/Details/{id}")]        public Employee Details(string id)        {            return objemployee.GetEmployeeData(id);        }        [HttpPut]        [Route("api/Employee/Edit")]        public void Edit([FromBody]Employee employee)        {            objemployee.UpdateEmployee(employee);        }        [HttpDelete]        [Route("api/Employee/Delete/{id}")]        public void Delete(string id)        {            objemployee.DeleteEmployee(id);        }        [HttpGet]        [Route("api/Employee/GetCities")]        public List<Cities> GetCities()        {            return objemployee.GetCityData();        }    }}

We have now finished the coding for our backend logic. Therefore, we will now proceed to code our client side.

现在,我们已经完成了后端逻辑的编码。 因此,我们现在开始对客户端进行编码。

创建视图组件 (Creating the View Component)

We will add the view page in BlazorWithMongo.Client/Pages folder. By default, we have “Counter” and “Fetch Data” pages provided in our application. These default pages will not affect our application. For the sake of this tutorial, we will delete fetchdata and counter pages from this folder.

我们将在BlazorWithMongo.Client/Pages文件夹中添加视图页面。 默认情况下,我们的应用程序中提供了“计数器”和“获取数据”页面。 这些默认页面不会影响我们的应用程序。 为了本教程的缘故,我们将从该文件夹中删除fetchdata计数器页面。

Right-click on BlazorWithMongo.Client/Pages folder and then select Add >> New Item. An “Add New Item” dialog box will open. Select “ASP.NET Core” from the left panel. Then select “Razor Page” from templates panel and name it EmployeeData.cshtml. Click Add. Refer to the image below:

右键单击BlazorWithMongo.Client/Pages文件夹,然后选择添加>>新建项目。 “添加新项”对话框将打开。 从左侧面板中选择“ ASP.NET Core”。 然后从模板面板中选择“ Razor Page”,并将其命名me it EmployeeData. cshtml。 单击添加。 请参考下图:

This will add an EmployeeData.cshtml page to our BlazorSPA.Client/Pages folder. This razor page will have two files – EmployeeData.cshtml and EmployeeData.cshtml.cs.

这会将EmployeeData.cshtml页面添加到我们的BlazorSPA.Client/Pages文件夹中。 此剃刀页面将包含两个文件-EmployeeData.cshtmlEmployeeData.cshtml.cs。

Now, we will add code to these pages.

现在,我们将代码添加到这些页面。

EmployeeData.cshtml (EmployeeData.cshtml)

Open EmployeeData.cshtml page and put the following code into it:

打开EmployeeData.cshtml页面,并将以下代码放入其中:

@page "/fetchemployee"@inherits EmployeeDataModel<h1>Employee Data</h1><h3>CRUD operation with Blazor using MongoDB</h3><br /><div>    <div style="float:left">        <button class="btn btn-primary" onclick="@AddEmp">Add Employee</button>    </div></div><br />@if (empList == null){    <p><em>Loading...</em></p>}else{    <table class='table'>        <thead>            <tr>                <th>Name</th>                <th>Gender</th>                <th>Department</th>                <th>City</th>            </tr>        </thead>        <tbody>            @foreach (var emp in empList)            {                <tr>                    <td>@emp.Name</td>                    <td>@emp.Gender</td>                    <td>@emp.Department</td>                    <td>@emp.City</td>                    <td>                        <button class="btn btn-info" onclick="@(async () => await EditEmployee(@emp.Id))">Edit</button>                        <button class="btn btn-danger" onclick="@(async () => await DeleteConfirm(@emp.Id))">Delete</button>                    </td>                </tr>            }        </tbody>    </table>    if (isAdd)    {        <div class="modal" tabindex="-1" style="display:block" role="dialog">            <div class="modal-dialog">                <div class="modal-content">                    <div class="modal-header">                        <h3 class="modal-title">@modalTitle</h3>                        <button type="button" class="close" onclick="@closeModal">                            <span aria-hidden="true">X</span>                        </button>                    </div>                    <div class="modal-body">                        <form>                            <div class="form-group">                                <label for="Name" class="control-label">Name</label>                                <input for="Name" class="form-control" bind="@emp.Name" />                            </div>                            <div class="form-group">                                <label asp-for="Gender" class="control-label">Gender</label>                                <select asp-for="Gender" class="form-control" bind="@emp.Gender">                                    <option value="">-- Select Gender --</option>                                    <option value="Male">Male</option>                                    <option value="Female">Female</option>                                </select>                            </div>                            <div class="form-group">                                <label asp-for="Department" class="control-label">Department</label>                                <input asp-for="Department" class="form-control" bind="@emp.Department" />                            </div>                            <div class="form-group">                                <label asp-for="City" class="control-label">City</label>                                <select asp-for="City" class="form-control" bind="@emp.City">                                    <option value="">-- Select City --</option>                                    @foreach (var city in cityList)                                    {                                        <option value="@city.CityName">@city.CityName</option>                                    }                                </select>                            </div>                        </form>                    </div>                    <div class="modal-footer">                        <button class="btn btn-block btn-success" onclick="@(async () => await SaveEmployee())" data-dismiss="modal">Save</button>                    </div>                </div>            </div>        </div>    }    if (isDelete)    {        <div class="modal" tabindex="-1" style="display:block" role="dialog">            <div class="modal-dialog">                <div class="modal-content">                    <div class="modal-header">                        <h3 class="modal-title">Delete Employee</h3>                    </div>                    <div class="modal-body">                        <h4>Do you want to delete this employee ??</h4>                        <table class="table">                            <tr>                                <td>Name</td>                                <td>@emp.Name</td>                            </tr>                            <tr>                                <td>Gender</td>                                <td>@emp.Gender</td>                            </tr>                            <tr>                                <td>Department</td>                                <td>@emp.Department</td>                            </tr>                            <tr>                                <td>City</td>                                <td>@emp.City</td>                            </tr>                        </table>                    </div>                    <div class="modal-footer">                        <button class="btn btn-danger" onclick="@(async () => await DeleteEmployee(emp.Id))" data-dismiss="modal">YES</button>                        <button class="btn btn-warning" onclick="@closeModal">NO</button>                    </div>                </div>            </div>        </div>    }}

Let us understand this code. At the top we have defined the route of this page as “/fetchemployee”. This means if we append “/fetchemployee” to the root URL of the app, we will be redirected to this page.

让我们了解这段代码。 在顶部,我们已将此页面的路线定义为“ / fetchemployee”。 这意味着,如果将“ / fetchemployee”附加到应用程序的根URL,我们将被重定向到此页面。

We are also inheriting EmployeeDataModel class, which is defined in EmployeeData.cshtml.cs file. This will allow us to use the methods defined in EmployeeDataModel class.

我们还将继承EmployeeDataModel类,该类在EmployeeData.cshtml.cs文件中定义。 这将使我们能够使用EmployeeDataModel类中定义的方法。

After this, we have defined a button to add a new employee record. When clicked, this button will open a modal popup to handle the user inputs.

此后,我们定义了一个添加新员工记录的按钮。 单击时,此按钮将打开一个模式弹出窗口以处理用户输入。

The list of employee documents returned from the database is stored in the empList variable. If the variable is not null then we will bind the values to a table to display the employee documents in a tabular fashion. Each row in the table has two action links. Edit to edit the employee document. Delete to delete the employee document.

从数据库返回的员工文档列表存储在empList变量中。 如果变量不为null,则将值绑定到表格以表格形式显示员工文档。 表中的每一行都有两个操作链接。 编辑以编辑员工文档。 删除以删除员工文档。

To handle the user inputs we are using a form. We are using a single form for both Add Employee and Edit Employee functionality. The form is defined in a modal popup and the modal popup is displayed on the screen based on the value of a Boolean property isAdd. The value of this Boolean property is set in the code behind (.cshtml.cs) page.

为了处理用户输入,我们使用表格。 我们正在为“添加员工”和“编辑员工”功能使用单一表格。 该表单在模式弹出窗口中定义,并且基于布尔属性isAdd的值在屏幕上显示模式弹出窗口。 在(.cshtml.cs)页面后面的代码中设置此布尔属性的值。

The City dropdown list inside the form is binding to our Cities collection in the database with the help of cityList variable. The cityList will be populated as the application boots up.

表单内的City下拉列表借助于cityList变量绑定到数据库中的Cities集合。 当应用程序启动时,将填充cityList。

The form will have a Save button which will invoke SaveEmployee method. This method is defined in the code behind file to Add or Update an employee document.

该窗体将具有一个保存按钮,它将调用SaveEmployee方法。 在添加或更新员工文档的文件后面的代码中定义了此方法。

Similar to the Add modal popup, we also have a Delete modal popup. It will be a read-only modal and will ask for a confirmation to delete an employee document. Upon clicking “Yes”, it will invoke the DeleteEmployee method to delete the employee document.

添加模式弹出窗口类似,我们还有一个删除模式弹出窗口。 这将是只读模式,将要求您确认删除员工文档。 单击“是”后,它将调用DeleteEmployee方法来删除员工文档。

EmployeeData.cshtml.cs (EmployeeData.cshtml.cs)

Open EmployeeData.cshtml.cs and put the following code into it:

打开EmployeeData.cshtml.cs并将以下代码放入其中:

using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Net.Http;using Microsoft.AspNetCore.Blazor;using Microsoft.AspNetCore.Blazor.Components;using BlazorWithMongo.Shared.Models;namespace BlazorWithMongo.Client.Pages{    public class EmployeeDataModel : BlazorComponent    {        [Inject]        protected HttpClient Http { get; set; }        protected List<Employee> empList;        protected List<Cities> cityList = new List<Cities>();        protected Employee emp = new Employee();        protected string modalTitle { get; set; }        protected Boolean isDelete = false;        protected Boolean isAdd = false;        protected string SearchString { get; set; }        protected override async Task OnInitAsync()        {            await GetEmployee();            await GetCities();        }        protected async Task GetEmployee()        {            empList = await Http.GetJsonAsync<List<Employee>>("api/Employee/Index");        }        protected async Task GetCities()        {            cityList = await Http.GetJsonAsync<List<Cities>>("api/Employee/GetCities");        }        protected void AddEmp()        {            emp = new Employee();            this.modalTitle = "Add Employee";            this.isAdd = true;        }        protected async Task EditEmployee(string ID)        {            emp = await Http.GetJsonAsync<Employee>("/api/Employee/Details/" + ID);            this.modalTitle = "Edit Employee";            this.isAdd = true;        }        protected async Task SaveEmployee()        {            if (emp.Id != null)            {                await Http.SendJsonAsync(HttpMethod.Put, "api/Employee/Edit", emp);            }            else            {                await Http.SendJsonAsync(HttpMethod.Post, "/api/Employee/Create", emp);            }            this.isAdd = false;            await GetEmployee();        }        protected async Task DeleteConfirm(string ID)        {            emp = await Http.GetJsonAsync<Employee>("/api/Employee/Details/" + ID);            this.isDelete = true;        }        protected async Task DeleteEmployee(string ID)        {            await Http.DeleteAsync("api/Employee/Delete/" + ID);            this.isDelete = false;            await GetEmployee();        }        protected void closeModal()        {            this.isAdd = false;            this.isDelete = false;        }    }}

In this file, we have defined a class EmployeeDataModel that will hold all the methods that we will be using in EmployeeData.cshtml page. We are also injecting the HttpClient service to enable web API calls.

在此文件中,我们定义了一个EmployeeDataModel类,该类将保存我们将在EmployeeData.cshtml页面中使用的所有方法。 我们还将注入HttpClient服务以启用Web API调用。

The variables empList and cityList are defined to hold the data from the Employee table and Cities table respectively. The variables are getting populated inside the OnInitAsync to make sure that the data is available to us as the page loads.

变量empListcityList定义为分别保存Employee表和Cities表中的数据。 这些变量将填充到OnInitAsync内部,以确保在页面加载时数据可供我们使用。

Clicking on the “Add Employee” button will invoke the AddEmp method. It will initialize an empty instance of Employee model and set the value of isAdd Boolean flag to true. This will open a modal popup with a form, asking the user to enter the value for a new employee document. Similarly, we have defined an EditEmployee method, which will fetch the record of the employee based on the Id for which it is invoked. It will also set the value of isAdd to true to open the modal popup to edit the employee document.

单击“添加员工”按钮将调用AddEmp方法。 它将初始化一个Employee模型的空实例,并将isAdd Boolean标志的值设置为true。 这将打开带有表单的模式弹出窗口,要求用户输入新员工文档的值。 同样,我们定义了一个EditEmployee方法,该方法将根据为其调用的ID来获取员工的记录。 还将isAdd的值设置为true,以打开模式弹出窗口以编辑员工文档。

The SaveEmployee method will check if it is invoked to add a new employee record or to edit an existing employee record. If the Id is not null, then it is an “edit” request and we will send a PUT request to the Web API to update the existing employee document.

SaveEmployee方法将检查是否调用了该方法以添加新的员工记录或编辑现有的员工记录。 如果Id不为null,则它是一个“编辑”请求,我们将向Web API发送一个PUT请求以更新现有的员工文档。

If the Id is null, then it is a “create” request and we will send a POST request to the Web API to create a new employee document.

如果Id为空,则它是一个“创建”请求,我们将向Web API发送POST请求以创建新的员工文档。

We will then fetch the updated list of employee documents by calling GetEmployee method. We also set the value of isAdd to false, thus closing the modal popup.

然后,我们将通过调用GetEmployee方法来获取更新的员工文档列表。 我们还将isAdd的值设置为false,从而关闭模式弹出窗口。

The DeleteConfirm method is invoked by clicking the Delete button corresponding to an employee record. It will set the value of isDelete Boolean flag to true, which will display a Delete confirmation modal popup. Upon clicking YES inside this popup, DeleteEmployee method is invoked. It sends a Delete Web API call to delete the employee document. It also sets the isDelete Boolean flag to false thus closing the modal popup.

通过单击与员工记录对应的Delete按钮来调用DeleteConfirm方法。 它将isDelete布尔标志的值设置为true,这将显示Delete确认模式弹出窗口。 在此弹出窗口中单击“是”后,将调用DeleteEmployee方法。 它发送一个Delete Web API调用以删除员工文档。 它还将isDelete布尔标志设置为false,从而关闭模式弹出窗口。

The last step is to add the link to our “EmployeeData” page in the navigation menu. Open the BlazorWithMongo/Shared/NavMenu.cshtml page and put the following code into it.

最后一步是将链接添加到导航菜单中的“ EmployeeData”页面。 打开BlazorWithMongo/Shared/NavMenu.cshtml页面,并将以下代码放入其中。

<div class="top-row pl-4 navbar navbar-dark">    <a class="navbar-brand" href="">BlazorWithMongo</a>    <button class="navbar-toggler" onclick=@ToggleNavMenu>        <span class="navbar-toggler-icon"></span>    </button></div><div class=@(collapseNavMenu ? "collapse" : null) onclick=@ToggleNavMenu>    <ul class="nav flex-column">        <li class="nav-item px-3">            <NavLink class="nav-link" href="" Match=NavLinkMatch.All>                <span class="oi oi-home" aria-hidden="true"></span> Home            </NavLink>        </li>        <li class="nav-item px-3">            <NavLink class="nav-link" href="fetchemployee">                <span class="oi oi-list-rich" aria-hidden="true"></span> Employee data            </NavLink>        </li>    </ul></div>@functions {bool collapseNavMenu = true;void ToggleNavMenu(){    collapseNavMenu = !collapseNavMenu;}}

Hence, we have successfully created a Single Page Application (SPA) using Blazor with the help of MongoDB as the database provider.

因此,我们已经在MongoDB的帮助下使用Blazor成功创建了单页应用程序(SPA),作为数据库提供程序。

执行演示 (Execution Demo)

Press F5 to launch the application.

按F5启动应用程序。

A web page will open as shown in the image below. The navigation menu on the left is showing the navigation link for the Employee data page.

如下图所示,将打开一个网页。 左侧的导航菜单显示Employee数据页面的导航链接。

Click on “Employee data” link, it will redirect to EmployeeData view. Here you can see all the employee data in a tabular fashion. Notice the URL has “/fetchemployee” appended to it.

单击“员工数据”链接,它将重定向到EmployeeData视图。 您可以在此处以表格形式查看所有员工数据。 请注意,URL附加了“ / fetchemployee”。

Click on the Add Employee button to open the “Add Employee” modal popup. Enter the data in all the fields and click on Save to create a new employee document.

单击添加员工按钮以打开“添加员工”模式弹出窗口。 在所有字段中输入数据,然后单击保存以创建新的员工文档。

This will create a new employee document and display the data in the View table. Click on Edit button corresponding to any row in the table, it will again open the modal popup for editing the employee record. Edit the input fields and click on save to update the employee document.

这将创建一个新的员工文档,并在“视图”表中显示数据。 单击与表中任何行相对应的“编辑”按钮,它将再次打开模式弹出窗口以编辑员工记录。 编辑输入字段,然后单击保存以更新员工文档。

If you click on the Delete button corresponding to the employee record, it will open a delete confirmation popup asking for a confirmation to delete the employee record.

如果单击与员工记录对应的“删除”按钮,它将打开一个删除确认弹出窗口,要求确认删除员工记录。

Clicking on YES will delete the employee data and show the updated list of employees by refreshing the view table.

单击“是”将删除员工数据,并通过刷新视图表来显示更新的员工列表。

结论 (Conclusion)

We have created a Single Page Application (SPA) using Blazor with the help of MongoDB as the database provider. We created a sample employee record management system and performed CRUD operations on it. To handle the user input, we used a form in a modal popup. We have used Visual Studio 2017 and MongoDB 4.0 for our demo.

我们已经在MongoDB的帮助下使用Blazor创建了单页应用程序(SPA),作为数据库提供程序。 我们创建了一个示例员工记录管理系统,并对它执行了CRUD操作。 为了处理用户输入,我们在模式弹出窗口中使用了一个表单。 我们已将Visual Studio 2017和MongoDB 4.0用于我们的演示。

Please get the source code from GitHub and play around to get a better understanding.

请从GitHub获取源代码并进行尝试以获得更好的理解。

Get my book Blazor Quick Start Guide to learn more about Blazor.

获取我的书《 Blazor快速入门指南》,以了解有关Blazor的更多信息。

You can check out my other articles here.

您可以在这里查看我的其他文章。

Preparing for interviews? Read my article on C# Coding Questions For Technical Interviews.

准备面试吗? 阅读有关技术面试的C#编码问题的文章。

也可以看看 (See Also)

Originally published at https://ankitsharmablogs.com/

最初发布在https://ankitsharmablogs.com/

翻译自: https://www.freecodecamp.org/news/how-to-perform-crud-operations-using-blazor-with-mongodb-8ee216ad513e/

mongodb 命令执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值