2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > vue.js crud_如何使用VS Code和ADO.NET使用ASP.NET Core执行CRUD操作

vue.js crud_如何使用VS Code和ADO.NET使用ASP.NET Core执行CRUD操作

时间:2023-04-18 17:21:19

相关推荐

vue.js crud_如何使用VS Code和ADO.NET使用ASP.NET Core执行CRUD操作

vue.js crud

介绍 (Introduction)

In this article we are going to create a web application using Core MVC with the help of Visual Studio Code and . We will be creating a sample Employee Record Management System and performing CRUD operations on it.

在本文中,我们将借助Visual Studio Code和使用 Core MVC创建一个Web应用程序。 我们将创建一个示例员工记录管理系统并在其上执行CRUD操作。

We will use VS Code and SQL Server for our demo.

我们将在演示中使用VS Code和SQL Server。

先决条件 (Prerequisites)

Install .NET Core 2.0.0 or above SDK from here

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

Download and install Visual Studio Code from here

从此处下载并安装Visual Studio Code

SQL Server or aboveSQL Server 或以上

源代码 (Source Code)

Before proceeding further, I would recommend that you download the source code from GitHub.

在继续进行之前,我建议您从GitHub下载源代码。

创建表和存储过程 (Creating the Table and Stored Procedures)

We will be using a DB table to store all the records of the employees.

我们将使用一个数据库表来存储员工的所有记录。

Open SQL Server and use the following script to createtblEmployeetable.

打开SQL Server并使用以下脚本创建tblEmployee表。

Create table tblEmployee( EmployeeId int IDENTITY(1,1) NOT NULL, Name varchar(20) NOT NULL, City varchar(20) NOT NULL, Department varchar(20) NOT NULL, Gender varchar(6) NOT NULL )

Now, we will create stored procedures to add, delete, update, and get employee data.

现在,我们将创建存储过程以添加,删除,更新和获取员工数据。

插入员工记录 (To Insert an Employee Record)

Create procedure spAddEmployee ( @Name VARCHAR(20), @City VARCHAR(20), @Department VARCHAR(20), @Gender VARCHAR(6) ) as Begin Insert into tblEmployee (Name,City,Department, Gender) Values (@Name,@City,@Department, @Gender) End

更新员工记录 (To Update an Employee Record)

Create procedure spUpdateEmployee( @EmpId INTEGER , @Name VARCHAR(20), @City VARCHAR(20), @Department VARCHAR(20), @Gender VARCHAR(6) )asbegin Update tblEmployee set Name=@Name, City=@City, Department=@Department, Gender=@Gender where EmployeeId=@EmpIdEnd

删除员工记录 (To Delete an Employee Record)

Create procedure spDeleteEmployee ( @EmpId int)as begin Delete from tblEmployee where EmployeeId=@EmpIdEnd

查看所有员工记录 (To View all Employee Records)

Create procedure spGetAllEmployeesasBeginselect *from tblEmployee order by EmployeeId End

Now, our Database part has been completed. So we will proceed to create the MVC application using Visual Studio code.

现在,我们的数据库部分已经完成。 因此,我们将继续使用Visual Studio代码创建MVC应用程序。

创建MVC Web应用程序 (Create the MVC Web Application)

We will be creating a source project from the terminal window in Visual Studio Code. Open VS code and navigate to view >> Integrated Terminal.

我们将在Visual Studio Code的终端窗口中创建一个源项目。 打开VS代码并浏览以查看>>集成终端。

This will open the terminal window as shown in the image below.

如下图所示,这将打开终端窗口。

Type the following sequence of commands in the terminal window. It will create our MVC application “MvcAdoDemo”.

在终端窗口中键入以下命令序列。 它将创建我们的MVC应用程序“ MvcAdoDemo”。

mkdir MvcAdoDemomkdir MvcAdoDemo cd MvcAdoDemocd MvcAdoDemo dotnet new mvcdotnet新的mvc

Now open this “MvcAdoDemo” project file using VS code. If it prompts the message “Required assets to build and debug are missing from MvcAdoDemo. Add them?”, select “Yes”.

现在,使用VS代码打开此“ MvcAdoDemo”项目文件。 如果它提示消息“ MvcAdoDemo中缺少构建和调试所需的资产。 要添加吗?”,选择“是”。

You can observe in the solution explorer that we already have folders created with the names Controllers, Models, and Views. We will be adding our code files in these folders only.

您可以在解决方案资源管理器中观察到,我们已经创建了名为Controllers,Models和Views的文件夹。 我们将仅在这些文件夹中添加代码文件。

将模型添加到应用程序 (Adding the Model to the Application)

Right click on Models folder and select “New File”. Name itEmployee.cs.It will create a file inside the Models folder.

右键单击“模型”文件夹,然后选择“新文件”。 将其命名为Employee.cs。它将在“模型”文件夹中创建一个文件。

Add one more file to the Models folder. Name itEmployeeDataAccessLayer.cs.This class will contain our Database-related operations.

在“模型”文件夹中再添加一个文件。 将其命名为EmployeeDataAccessLayer.cs。此类将包含与数据库相关的操作。

OpenEmployee.csand put following code inside it.Since we are adding the required validators to the fields of Employee class, we need to use ponentModel.DataAnnotations at the top:

打开Employee.cs并在其中放入以下代码。由于我们将必需的验证器添加到Employee类的字段中,因此我们需要在顶部使用ponentModel.DataAnnotations:

using System; using System.Collections.Generic; using ponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace MVCAdoDemo.Models { public class Employee { public int ID { get; set; } [Required] public string Name { get; set; } [Required] public string Gender { get; set; } [Required] public string Department { get; set; } [Required] public string City { get; set; } } }

OpenEmployeeDataAccessLayer.csand put in the following code to handle database operations. Make sure to put in your own connection string.

打开EmployeeDataAccessLayer.cs并放入以下代码来处理数据库操作。 确保输入您自己的连接字符串。

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace MVCAdoDemo.Models { public class EmployeeDataAccessLayer { string connectionString = "Your Connection String here";//To View all employees details public IEnumerable<Employee> GetAllEmployees() {List<Employee> lstemployee = new List<Employee>();using (SqlConnection con = new SqlConnection(connectionString)){SqlCommand cmd = new SqlCommand("spGetAllEmployees", con);mandType = CommandType.StoredProcedure; con.Open();SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()){ Employee employee = new Employee(); employee.ID = Convert.ToInt32(rdr["EmployeeID"]); employee.Name = rdr["Name"].ToString(); employee.Gender = rdr["Gender"].ToString(); employee.Department = rdr["Department"].ToString(); employee.City = rdr["City"].ToString(); lstemployee.Add(employee);}con.Close();}return lstemployee; }//To Add new employee record public void AddEmployee(Employee employee) {using (SqlConnection con = new SqlConnection(connectionString)){SqlCommand cmd = new SqlCommand("spAddEmployee", con);mandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Name", employee.Name);cmd.Parameters.AddWithValue("@Gender", employee.Gender);cmd.Parameters.AddWithValue("@Department", employee.Department);cmd.Parameters.AddWithValue("@City", employee.City); con.Open();cmd.ExecuteNonQuery();con.Close();} }//To Update the records of a particluar employee public void UpdateEmployee(Employee employee) {using (SqlConnection con = new SqlConnection(connectionString)){SqlCommand cmd = new SqlCommand("spUpdateEmployee", con);mandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@EmpId", employee.ID);cmd.Parameters.AddWithValue("@Name", employee.Name);cmd.Parameters.AddWithValue("@Gender", employee.Gender);cmd.Parameters.AddWithValue("@Department", employee.Department);cmd.Parameters.AddWithValue("@City", employee.City); con.Open();cmd.ExecuteNonQuery();con.Close();} }//Get the details of a particular employee public Employee GetEmployeeData(int? id) {Employee employee = new Employee();using (SqlConnection con = new SqlConnection(connectionString)){string sqlQuery = "SELECT * FROM tblEmployee WHERE EmployeeID= " + id;SqlCommand cmd = new SqlCommand(sqlQuery, con); con.Open();SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()){ employee.ID = Convert.ToInt32(rdr["EmployeeID"]); employee.Name = rdr["Name"].ToString(); employee.Gender = rdr["Gender"].ToString(); employee.Department = rdr["Department"].ToString(); employee.City = rdr["City"].ToString();}}return employee; }//To Delete the record on a particular employee public void DeleteEmployee(int? id) {using (SqlConnection con = new SqlConnection(connectionString)){SqlCommand cmd = new SqlCommand("spDeleteEmployee", con);mandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@EmpId", id); con.Open();cmd.ExecuteNonQuery();con.Close();} } } }

To use functionalities in VS code, we need to add the nuget package reference toSystem.Data.SqlClient.Open theMvcAdoDemo.csprojfile and put the following code into it.

要在VS代码中使用功能,我们需要将nuget包引用添加到System.Data.SqlClient中。打开MvcAdoDemo.csproj文件,并将以下代码放入其中。

<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />

Put this code in the location highlighted in the image below.

将此代码放在下图中突出显示的位置。

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

Right click on the Controllers folder and select “New File”. Name itEmployeeController.cs.It will create a new file inside the Controllers folder.

右键单击Controllers文件夹,然后选择“ New File”。 将其命名为EmployeeController.cs。它将在Controllers文件夹内创建一个新文件。

Now ourEmployeeControllerhas been created. We will put all our business logic in this controller.

现在我们的EmployeeController已经被创造了。 我们将所有业务逻辑放入此控制器中。

向应用程序添加视图 (Adding Views to the Application)

To add views for our controller class, we need to create a folder inside theViewsfolder with the same name as our controller and then add our views to that folder.

要为我们的控制器类添加视图,我们需要在视图内部创建一个文件夹与控制器名称相同的文件夹,然后将视图添加到该文件夹​​。

Right-click on the Viewsfolder, and select “New Folder” and name the folderEmployee.

右键单击视图文件夹,然后选择“新建文件夹”,并将文件夹命名为Employee

To add view files, right click on the Employee folder inside the Views folder and select “New File”. Name itIndex.cshtml.This will create a view file inside Employee folder.Thus, we have created our first view. Similarly add 4 more views in the Views/Employee folder:Create.cshtml, Delete.cshtml, Details.cshtml,andandEdit.cshtml.

要添加视图文件,请在Views文件夹内的Employee文件夹上单击鼠标右键,然后选择“ New File”。 将其命名为Index.cshtml。这将在Employee文件夹中创建一个视图文件。因此,我们创建了第一个视图。 同样,在“视图/雇员”文件夹中添加另外4个视图:Create.cshtml,Delete.cshtml,Details.cshtmlandEdit.cshtml。

Now our Views folder will look like this:

现在,我们的“视图”文件夹将如下所示:

Since all our Views have been created, we will put some code in View and Controller for performing CRUD operations.

由于我们所有的视图均已创建,因此我们将在View和Controller中放置一些代码以执行CRUD操作。

索引检视 (Index View)

This view will display all the employee records present in the database. Additionally, we will also provide the action methods Edit, Details, and Delete on each record.

该视图将显示数据库中存在的所有员工记录。 此外,我们还将在每个记录上提供操作方法“编辑”,“详细信息”和“删除”。

OpenIndex.cshtmland put the following code in it.

打开Index.cshtml并将以下代码放入其中。

@model IEnumerable<MVCAdoDemo.Models.Employee> @{ ViewData["Title"] = "Index"; } <h2>Index</h2> <p> <a asp-action="Create">Create New</a> </p> <table class="table"> <thead> <tr><th>@Html.DisplayNameFor(model => model.Name)</th><th>@Html.DisplayNameFor(model => model.Gender)</th><th>@Html.DisplayNameFor(model => model.Department)</th><th>@Html.DisplayNameFor(model => model.City)</th><th></th> </tr> </thead> <tbody> @foreach (var item in Model) {<tr><td> @Html.DisplayFor(modelItem => item.Name)</td><td> @Html.DisplayFor(modelItem => item.Gender)</td><td> @Html.DisplayFor(modelItem => item.Department)</td><td> @Html.DisplayFor(modelItem => item.City)</td><td> <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> | <a asp-action="Details" asp-route-id="@item.ID">Details</a> | <a asp-action="Delete" asp-route-id="@item.ID">Delete</a></td></tr> } </tbody> </table>

Open yourEmployeeController.csfile.You’ll see that it is empty. Put the following code into it.

打开您的EmployeeController.cs文件。您会看到它是空的。 将以下代码放入其中。

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MVCAdoDemo.Models; namespace MVCAdoDemo.Controllers {public class EmployeeController : Controller{EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer(); public IActionResult Index(){ List<Employee> lstEmployee = new List<Employee>(); lstEmployee = objemployee.GetAllEmployees().ToList();return View(lstEmployee);} } }

To handle database operations, we have created an object ofEmployeeDataAccessLayerclass inside theEmployeeControllerclass.

为了处理数据库操作,我们创建了一个EmployeeDataAccessLayer对象EmployeeController内部的类类。

建立检视 (Create View)

This view will be used to Add new employee data to the database.

该视图将用于向数据库添加新员工数据。

OpenCreate.cshtmland put the following code into it.

打开Create.cshtml并将以下代码放入其中。

@model MVCAdoDemo.Models.Employee @{ ViewData["Title"] = "Create"; } <h2>Create</h2> <h4>Employees</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Create"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Name" class="control-label"></label><input asp-for="Name" class="form-control" /><span asp-validation-for="Name" class="text-danger"></span></div><div class="form-group"><label asp-for="Gender" class="control-label"></label><select asp-for="Gender" class="form-control"> <option value="">-- Select Gender --</option> <option value="Male">Male</option> <option value="Female">Female</option></select><span asp-validation-for="Gender" class="text-danger"></span></div><div class="form-group"><label asp-for="Department" class="control-label"></label><input asp-for="Department" class="form-control" /><span asp-validation-for="Department" class="text-danger"></span></div><div class="form-group"><label asp-for="City" class="control-label"></label><input asp-for="City" class="form-control" /><span asp-validation-for="City" class="text-danger"></span></div><div class="form-group"><input type="submit" value="Create" class="btn btn-default" /></div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

To handle the business logic ofcreate, openEmployeeController.csand put the following code into it.

要处理create的业务逻辑,请打开EmployeeController.cs并将以下代码放入其中。

[HttpGet] public IActionResult Create() {return View(); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Create([Bind] Employee employee) {if (ModelState.IsValid){objemployee.AddEmployee(employee);return RedirectToAction("Index");}return View(employee); }

The [Bind] attribute is used with parameter “employee” to protect against over-posting. To learn more about over-posting, visit this link.

[Bind]属性与参数“ employee”一起使用,以防止发布过多信息。 要了解有关过度发布的更多信息,请访问此链接。

编辑视图 (Edit View)

This view will enable us to edit an existing employee’s data.

此视图将使我们能够编辑现有员工的数据。

OpenEdit.cshtmland put the following code into it.

打开Edit.cshtml并将以下代码放入其中。

@model MVCAdoDemo.Models.Employee @{ ViewData["Title"] = "Edit"; } <h2>Edit</h2> <h4>Employees</h4> <hr /> <div class="row"> <div class="col-md-4"> <form asp-action="Edit"><div asp-validation-summary="ModelOnly" class="text-danger"></div><input type="hidden" asp-for="ID" /><div class="form-group"><label asp-for="Name" class="control-label"></label><input asp-for="Name" class="form-control" /><span asp-validation-for="Name" class="text-danger"></span></div><div class="form-group"><label asp-for="Gender" class="control-label"></label><select asp-for="Gender" class="form-control"> <option value="">-- Select Gender --</option> <option value="Male">Male</option> <option value="Female">Female</option></select><span asp-validation-for="Gender" class="text-danger"></span></div><div class="form-group"><label asp-for="Department" class="control-label"></label><input asp-for="Department" class="form-control" /><span asp-validation-for="Department" class="text-danger"></span></div><div class="form-group"><label asp-for="City" class="control-label"></label><input asp-for="City" class="form-control" /><span asp-validation-for="City" class="text-danger"></span></div> <div class="form-group"><input type="submit" value="Save" class="btn btn-default" /></div> </form> </div> </div> <div> <a asp-action="Index">Back to List</a> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

To handle the business logic of theEditview, openEmployeeController.csand add the following code to it.

要处理“编辑”视图的业务逻辑,请打开EmployeeController.cs并添加以下代码。

[HttpGet] public IActionResult Edit(int? id) {if (id == null){return NotFound();}Employee employee = objemployee.GetEmployeeData(id); if (employee == null){return NotFound();}return View(employee); } [HttpPost] [ValidateAntiForgeryToken] public IActionResult Edit(int id, [Bind]Employee employee) {if (id != employee.ID){return NotFound();}if (ModelState.IsValid){objemployee.UpdateEmployee(employee);return RedirectToAction("Index");}return View(employee); }

You’ll see that we have two Edit action methods: one for HttpGet and another for HttpPost.The HttpGet Edit action method fetches the employee data and populates the fields of edit view. Once the user clicks on the Save button after editing the record, a Post request will be generated which is handled by the HttpPost Edit action method.

您会看到我们有两个Edit操作方法:一个用于HttpGet,另一个用于HttpPost.HttpGet Edit操作方法获取员工数据并填充编辑视图的字段。 用户在编辑记录后单击“保存”按钮后,将生成一个Post请求,该请求由HttpPost Edit操作方法处理。

详细资料检视 (Details View)

This view will display the details of a particular employee.

该视图将显示特定员工的详细信息。

OpenDetails.cshtmland put the following code into it.

打开Details.cshtml并将以下代码放入其中。

@model MVCAdoDemo.Models.Employee @{ ViewData["Title"] = "Details"; } <h2>Details</h2> <div> <h4>Employees</h4> <hr /> <dl class="dl-horizontal"> <dt>@Html.DisplayNameFor(model => model.Name) </dt> <dd>@Html.DisplayFor(model => model.Name) </dd> <dt>@Html.DisplayNameFor(model => model.Gender) </dt> <dd>@Html.DisplayFor(model => model.Gender) </dd> <dt>@Html.DisplayNameFor(model => model.Department) </dt> <dd>@Html.DisplayFor(model => model.Department) </dd> <dt>@Html.DisplayNameFor(model => model.City) </dt> <dd>@Html.DisplayFor(model => model.City) </dd> </dl> </div> <div> <a asp-action="Edit" asp-route-id="@Model.ID">Edit</a> | <a asp-action="Index">Back to List</a> </div>

To handle the business logic of theDetailsview, openEmployeeController.csand add the following code to it.

要处理“详细信息”视图的业务逻辑,请打开EmployeeController.cs并添加以下代码。

[HttpGet] public IActionResult Details(int? id) {if (id == null){return NotFound();}Employee employee = objemployee.GetEmployeeData(id); if (employee == null){return NotFound();}return View(employee); }

删除检视 (Delete View)

This view will help us to remove employee data.

此视图将帮助我们删除员工数据。

OpenDelete.cshtmland put the following code into it.

打开Delete.cshtml并将以下代码放入其中。

@model MVCAdoDemo.Models.Employee @{ ViewData["Title"] = "Delete"; } <h2>Delete</h2> <h3>Are you sure you want to delete this?</h3> <div> <h4>Employees</h4> <hr /> <dl class="dl-horizontal"> <dt>@Html.DisplayNameFor(model => model.Name) </dt> <dd>@Html.DisplayFor(model => model.Name) </dd> <dt>@Html.DisplayNameFor(model => model.Gender) </dt> <dd>@Html.DisplayFor(model => model.Gender) </dd> <dt>@Html.DisplayNameFor(model => model.Department) </dt> <dd>@Html.DisplayFor(model => model.Department) </dd> <dt>@Html.DisplayNameFor(model => model.City) </dt> <dd>@Html.DisplayFor(model => model.City) </dd> </dl> <form asp-action="Delete"> <input type="hidden" asp-for="ID" /> <input type="submit" value="Delete" class="btn btn-default" /> | <a asp-action="Index">Back to List</a> </form> </div>

To handle the business logic of theDeleteview, openEmployeeController.csand add the following code to it.

要处理Delete视图的业务逻辑,请打开EmployeeController.cs并添加以下代码。

[HttpGet] public IActionResult Delete(int? id) {if (id == null){return NotFound();}Employee employee = objemployee.GetEmployeeData(id); if (employee == null){return NotFound();}return View(employee); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public IActionResult DeleteConfirmed(int? id) {objemployee.DeleteEmployee(id);return RedirectToAction("Index"); }

To complete the Delete operation, we need two Delete methods that accept the same parameter (Employee Id). But two methods with same name and method signature will create a compile time error. And if we rename the Delete method, then routing won’t be able to find it, as maps URL segments to action methods by name.

要完成Delete操作,我们需要两个接受相同参数(员工ID)的Delete方法。 但是具有相同名称和方法签名的两个方法将产生编译时错误。 而且,如果我们重命名Delete方法,则路由将无法找到它,因为按名称将URL段映射到操作方法。

So, to resolve this issue, we add the ActionName(“Delete”) attribute to the DeleteConfirmed method. This attribute performs mapping for the routing system so that a URL that includes /Delete/ for a POST request will find the DeleteConfirmed method.

因此,为解决此问题,我们将ActionName(“ Delete”)属性添加到DeleteConfirmed方法。 此属性为路由系统执行映射,以便包含POST请求的/ Delete /的URL将找到DeleteConfirmed方法。

When we click on the Delete link on the Index page, it will send a Get request and return a View of the employee using the HttpGet Delete method. When we click on the Delete button on this view, it will send a Post request to delete the record which is handled by the HttpPost DeleteConfirmed method.

当我们单击“索引”页面上的“删除”链接时,它将发送一个Get请求并使用HttpGet Delete方法返回该员工的视图。 当我们单击该视图上的Delete按钮时,它将发送一个Post请求以删除由HttpPost DeleteConfirmed方法处理的记录。

Performing a delete operation in response to a Get request (or, for that matter, performing an edit operation, create operation, or any other operation that changes data) opens up a security hole. Therefore, we have two separate methods.

响应于Get请求执行删除操作(或者,执行编辑操作,创建操作或更改数据的任何其他操作)打开了一个安全漏洞。 因此,我们有两种不同的方法。

配置路由URL (Configure the route URL)

Before launching the application, we will configure the route URLs. Open theStartup.csfile to set the format for routing. Scroll down to theapp.UseMvcmethod, where you can set the route URL.

在启动应用程序之前,我们将配置路由URL。 打开Startup.cs文件以设置路由格式。 向下滚动到app.UseMvc方法,您可以在其中设置路由URL。

Make sure that your route URL is set like this:

确保您的路线网址设置如下:

app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });

This URL pattern sets HomeController as the default controller and Index method as the default action method (whereas the Id parameter is optional). Default and optional route parameters need not be present in the URL path for a match.

此URL模式将HomeController设置为默认控制器,并将Index方法设置为默认操作方法(而Id参数是可选的)。 匹配的URL路径中不必包含默认和可选的路由参数。

If we do not append any controller name in the URL, then it will take HomeController as the default controller and the Index method of HomeController as the default action method. Similarly, if we append only the Controller name in the URL, it will navigate to the Index action method of that controller.

如果我们在U​​RL中未添加任何控制器名称,则它将使用HomeController作为默认控制器,并使用HomeController的Index方法作为默认操作方法。 同样,如果我们仅在URL中附加控制器名称,它将导航到该控制器的Index操作方法。

执行演示 (Execution Demo)

Now press F5 to launch the application and navigate to the Employee controller by appending/Employeeto the URL.

现在按F5键启动应用程序,并通过添加/ Employee导航到Employee控制器URL。

You can see the page as shown below.

您可以看到如下所示的页面。

Click onCreateNewto navigate to theCreateview. Add a new Employee record as shown in the image below.

单击CreateNew导航到Create视图。 如下图所示添加新的Employee记录。

If we miss the data in any field while creating the employee record, we will get a required field validation error message.

如果在创建员工记录时错过任何字段中的数据,我们将收到必填字段验证错误消息。

After inserting the data in all the fields, click on the “Create” button. The new employee record will be created and you will be redirected to the Index view, which displays records of all the employees. Here, we can also see the action methods Edit, Details, and Delete.

在所有字段中插入数据后,单击“创建”按钮。 将创建新的员工记录,并将您重定向到索引视图,该视图显示所有员工的记录。 在这里,我们还可以看到操作方法“编辑”,“详细信息”和“删除”。

If we want to edit an existing employee record, then click the Edit action link. It will open the Edit View as below where we can change the employee’s data.

如果我们要编辑现有员工记录,请单击“编辑操作”链接。 它将打开如下所示的“编辑”视图,我们可以在其中更改员工的数据。

Here we have changed the City of employee Dhiraj from Mumbai to New Delhi. Click on “Save” to return to the Index view to see the updated changes as highlighted in the image below.

在这里,我们将员工Dhiraj市从孟买更改为新德里。 单击“保存”返回到索引视图,以查看更新的更改,如下图所示。

If we miss any fields while editing the employee’s record, then the Edit view will also throw the required field validation error message.

如果在编辑员工记录时错过任何字段,那么“编辑”视图还将抛出必填字段验证错误消息。

If you want to see the details of any Employee, then click on the Details action link, which will open the Details view, as shown in the image below.

如果要查看任何员工的详细信息,请单击“详细信息”操作链接,这将打开“详细信息”视图,如下图所示。

Click on “Back to List” to go back to Index view. Now, we will perform a Delete operation on an employee named Rahul. Click on the Delete action link which will open the Delete view asking for a confirmation to delete.

单击“返回列表”以返回索引视图。 现在,我们将对名为Rahul的员工执行Delete操作。 单击删除操作链接,这将打开“删除”视图,要求您确认删除。

Once we click on the Delete button, it will send an HttpPost request to delete the employee’s record, and we will be redirected to the Index view. Here, we can see that the employee with the name Rahul has been removed from our record.

单击删除按钮后,它将发送HttpPost请求以删除员工的记录,然后我们将被重定向到索引视图。 在这里,我们可以看到名为Rahul的员工已从我们的记录中删除。

结论 (Conclusion)

We have learned about creating a sample MVC web application using Core 2.0, , and a SQL server with the help of Visual Studio Code.

我们已经了解了如何在Visual Studio Code的帮助下使用 Core 2.0,和SQL Server创建示例MVC Web应用程序。

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

从GitHub下载源代码,然后玩转以获得更好的理解。

You can check my other articles on ASP .NET Core here

您可以在此处查看有关ASP .NET Core的其他文章

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

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

也可以看看 (See Also)

CRUD Operation With Core MVC Using and Visual Studio

使用和Visual Studio 的 Core MVC进行CRUD操作

CRUD Operation With Core MVC Using Visual Studio Code and EF

使用Visual Studio Code和EF使用 Core MVC进行CRUD操作

Core — CRUD With React.js And Entity Framework Core

Core —使用React.js和实体框架Core的CRUD

CRUD Operations With Core Using Angular 5 and

使用Angular 5和的 Core的CRUD操作

Core — Getting Started With Blazor

Core — Blazor入门

Cookie Authentication With Core 2.0

使用 Core 2.0进行Cookie身份验证

Originally published at

最初发布在

翻译自: /news/how-to-perform-crud-operations-with-asp-net-core-using-vs-code-and-ado-net-b12404aef708/

vue.js crud

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。