📜  ASP.NET WP-将数据添加到数据库

📅  最后修改于: 2020-11-21 05:30:41             🧑  作者: Mango


在本章中,我们将介绍如何创建一个页面,该页面允许用户将数据添加到数据库的“客户”表中。

  • 在此示例中,您还将了解何时插入记录,然后该页面使用我们在上一章中创建的ListCustomers.cshtml页面显示更新的表。

  • 在此页面中,我们还添加验证以确保用户输入的数据对数据库有效。例如,用户已经输入了所有必填列的数据。

如何将数据添加到数据库中的客户表?

让我们向您的网站添加一个新的CSHTML文件。

表中数据

在“名称”字段中输入InsertCustomer.cshtml ,然后单击“确定”。

现在,创建一个新的网页,用户可以在其中将数据插入“客户”表中,因此用以下代码替换InsertCustomer.cshtml文件。

@{
   Validation.RequireField("FirstName", "First Name is required.");
   Validation.RequireField("LastName", "Last Name is required.");
   Validation.RequireField("Address", "Address is required.");
   
   var db = Database.Open("WebPagesCustomers");
   var FirstName = Request.Form["FirstName"];
   var LastName = Request.Form["LastName"];
   var Address = Request.Form["Address"];
   
   if (IsPost && Validation.IsValid()) {
      // Define the insert query. The values to assign to the
      // columns in the Customers table are defined as parameters
      // with the VALUES keyword.
      
      if(ModelState.IsValid) {
         var insertQuery = "INSERT INTO Customers (FirstName, LastName, Address) " +
            "VALUES (@0, @1, @2)";
         db.Execute(insertQuery, FirstName, LastName, Address);
         
         // Display the page that lists products.
         Response.Redirect("~/ListCustomers");
      }
   }
}



   
   
      Add Customer
      
   
   
   
      

Add New Customer

@Html.ValidationSummary("Errors with your submission:")
Add Customer

现在,让我们运行该应用程序并指定以下URL- http:// localhost:36905 / InsertCustomer ,您将看到以下网页。

插入客户

在上面的屏幕截图中,您可以看到我们已经添加了验证,因此您在不输入任何数据的情况下单击插入按钮,或者错过了上述任何字段,然后您将看到它显示错误消息,如以下屏幕截图所示。

错误信息

现在,让我们在所有字段中输入一些数据。

输入数据

现在单击“插入”,您将看到更新的客户列表,如以下屏幕截图所示。

更新清单