- ASP.NET WP 教程
- ASP.NET WP - 首页
- ASP.NET WP - 概述
- ASP.NET WP - 环境设置
- ASP.NET WP - 入门
- ASP.NET WP - 视图引擎
- 项目文件夹结构
- ASP.NET WP - 全局页面
- ASP.NET WP - 编程概念
- ASP.NET WP - 布局
- ASP.NET WP - 使用表单
- ASP.NET WP - 页面对象模型
- ASP.NET WP - 数据库
- ASP.NET WP - 向数据库添加数据
- ASP.NET WP - 编辑数据库数据
- ASP.NET WP - 删除数据库数据
- ASP.NET WP - WebGrid
- ASP.NET WP - 图表
- ASP.NET WP - 使用文件
- ASP.NET WP - 使用图像
- ASP.NET WP - 使用视频
- ASP.NET WP - 添加电子邮件
- ASP.NET WP - 添加搜索
- 向网站添加社交网络功能
- ASP.NET WP - 缓存
- ASP.NET WP - 安全性
- ASP.NET WP - 发布
- ASP.NET WP 有用资源
- ASP.NET WP - 快速指南
- ASP.NET WP - 有用资源
- ASP.NET WP - 讨论
ASP.NET WP - 向数据库添加数据
在本节中,我们将介绍如何创建一个页面,允许用户向数据库中的 Customers 表添加数据。
在本例中,您还将了解当记录插入后,页面如何使用我们在上一节中创建的 ListCustomers.cshtml 页面显示更新后的表格。
在此页面中,我们还添加了验证,以确保用户输入的数据对数据库有效。例如,用户已为所有必填列输入数据。
如何向数据库中的 Customer 表添加数据?
让我们向您的网站添加一个新的 CSHTML 文件。
在“名称”字段中输入 **InsertCustomer.cshtml**,然后单击“确定”。
现在创建一个新的网页,用户可以在其中插入 Customers 表中的数据,因此用以下代码替换 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");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Add Customer</title>
<style type = "text/css">
label {
float:left;
width: 8em;
text-align:
right;
margin-right: 0.5em;
}
fieldset {
padding: 1em;
border: 1px solid;
width: 50em;
}
legend {
padding: 2px 4px;
border: 1px solid;
font-weight:bold;
}
.validation-summary-errors {
font-weight:bold;
color:red;
font-size: 11pt;
}
</style>
</head>
<body>
<h1>Add New Customer</h1>
@Html.ValidationSummary("Errors with your submission:")
<form method = "post" action = "">
<fieldset>
<legend>Add Customer</legend>
<div>
<label>First Name:</label>
<input name = "FirstName" type = "text" size = "50" value = "@FirstName"/>
</div>
<div>
<label>Last Name:</label>
<input name = "LastName" type = "text" size = "50" value = "@LastName" />
</div>
<div>
<label>Address:</label>
<input name = "Address" type = "text" size = "50" value = "@Address" />
</div>
<div>
<label> </label>
<input type = "submit" value = "Insert" class = "submit" />
</div>
</fieldset>
</form>
</body>
</html>
现在让我们运行应用程序并指定以下 URL:**https://:36905/InsertCustomer**,您将看到以下网页。
在上面的屏幕截图中,您可以看到我们添加了验证,因此如果您在不输入任何数据或缺少上述任何字段的情况下单击“插入”按钮,您将看到它会显示错误消息,如下面的屏幕截图所示。
现在让我们在所有字段中输入一些数据。
现在单击“插入”,您将看到更新后的客户列表,如下面的屏幕截图所示。
广告