网页输入数据到mysql,引入 ASP.NET 网页使用窗体输入数据库数据

引入 ASP.NET 网页使用窗体输入数据库数据Introducing ASP.NET Web Pages - Entering Database Data by Using Forms

05/28/2015

本文内容

本教程介绍如何创建一个条目窗体,然后在使用 ASP.NET 网页(Razor)时,输入从窗体获取到数据库表中的数据。This tutorial shows you how to create an entry form and then enter the data that you get from the form into a database table when you use ASP.NET Web Pages (Razor). It assumes you have completed the series through Basics of HTML Forms in ASP.NET Web Pages.

学习内容:What you'll learn:

有关如何处理条目窗体的详细信息。More about how to process entry forms.

如何在数据库中添加(插入)数据。How to add (insert) data in a database.

如何确保用户已在表单中输入所需的值(如何验证用户输入)。How to make sure that users have entered a required value in a form (how to validate user input).

如何显示验证错误。How to display validation errors.

如何从当前页面跳转到另一个页面。How to jump to another page from the current page.

介绍的功能/技术:Features/technologies discussed:

Database.Execute 方法。The Database.Execute method.

SQL Insert Into 语句The SQL Insert Into statement

Validation 帮助程序。The Validation helper.

Response.Redirect 方法。The Response.Redirect method.

你将生成What You'll Build

在前面的教程中,介绍了如何创建数据库,通过直接在 WebMatrix 中编辑数据库来输入数据库数据,该数据库在数据库工作区中工作。In the tutorial earlier that showed you how to create a database, you entered database data by editing the database directly in WebMatrix, working in the Database workspace. 但在大多数应用中,这并不是将数据放入数据库的实用方法。In most apps, that's not a practical way to put data into the database, though. 在本教程中,您将创建一个基于 web 的界面,使您或任何人都可以输入数据并将其保存到数据库中。So in this tutorial, you'll create a web-based interface that lets you or anyone enter data and save it to the database.

你将创建一个可在其中输入新电影的页面。You'll create a page where you can enter new movies. 此页将包含一个输入窗体,其中包含可在其中输入电影标题、流派和年份的字段(文本框)。The page will contain an entry form that has fields (text boxes) where you can enter a movie title, genre, and year. 该页将如下所示:The page will look like this page:

f609fdd3cb7a5b12fb93d536f57a5734.png

文本框将是 HTML 元素,这些元素将类似于以下标记:The text boxes will be HTML elements that will look like this markup:

创建基本条目窗体Creating the Basic Entry Form

创建名为AddMovie的页。Create a page named AddMovie.cshtml.

将文件中的内容替换为以下标记。Replace what's in the file with the following markup. 覆盖所有内容;你将很快在顶部添加一个代码块。Overwrite everything; you'll add a code block at the top shortly.

Add a Movie

Add a Movie

Movie Information

Title:

Genre:

Year:

此示例演示用于创建窗体的典型 HTML。This example shows typical HTML for creating a form. 它使用文本框和提交按钮 元素。It uses elements for the text boxes and for the submit button. 文本框的标题是使用标准 元素创建的。The captions for the text boxes are created by using standard elements. 和 元素围绕窗体放置了一个不错的框。The and elements put a nice box around the form.

请注意,在此页中,

元素使用 post 作为 method 特性的值。Notice that in this page, the element uses post as the value for the method attribute. 在上一教程中,您创建了一个使用 get 方法的窗体。In the previous tutorial, you created a form that used the get method. 这是正确的,因为虽然表单已将值提交给服务器,但请求未进行任何更改。That was correct, because although the form submitted values to the server, the request did not make any changes. 它的所有操作都是以不同的方式获取数据。All it did was fetch data in different ways. 但是,在此页中你将进行更改,即你要添加新的数据库记录。However, in this page you will make changes—you're going to add new database records. 因此,此窗体应该使用 post 方法。Therefore, this form should use the post method. (有关 GET 和 POST 操作之间的差异的详细信息,请参阅上一教程中的GET、POST 和 HTTP Verb 安全侧栏。)(For more about the difference between GET and POST operations, see theGET, POST, and HTTP Verb Safety sidebar in the previous tutorial.)

请注意,每个文本框都有一个 name 元素(title、genre``year)。Note that each text box has a name element (title, genre, year). 正如你在上一教程中看到的那样,这些名称很重要,因为你必须具有这些名称,以便以后可以获取用户的输入。As you saw in the previous tutorial, these names are important because you must have those names so you can get the user's input later. 您可以使用任何名称。You can use any names. 使用有意义的名称有助于记住正在处理的数据,这会很有帮助。It's helpful to use meaningful names that help you remember what data you're working with.

每个 元素的 value 属性包含一个 Razor 代码(例如 Request.Form["title"])。The value attribute of each element contains a bit of Razor code (for example, Request.Form["title"]). 在上一教程中,你已学习了此技巧的一个版本,可在提交窗体后保留输入到文本框中的值(如果有)。You learned a version of this trick in the previous tutorial to preserve the value entered into the text box (if any) after the form has been submitted.

获取窗体值Getting the Form Values

接下来,添加处理窗体的代码。Next, you add code that processes the form. 在大纲中,你将执行以下操作:In outline, you'll do the following:

检查页面是否正在发布(已提交)。Check whether the page is being posted (was submitted). 只需在用户单击该按钮时(而不是在页面首次运行时)运行。You want to your code to run only when users have clicked the button, not when the page first runs.

获取用户输入到文本框中的值。Get the values that the user entered into the text boxes. 在这种情况下,由于窗体使用的是 POST 谓词,因此从 Request.Form 集合获取窗体值。In this case, because the form is using the POST verb, you get the form values from the Request.Form collection.

将值作为新记录插入到电影数据库表中。Insert the values as a new record in the Movies database table.

在该文件的顶部,添加以下代码:At the top of the file, add the following code:

@{

var title = "";

var genre = "";

var year = "";

if(IsPost){

title = Request.Form["title"];

genre = Request.Form["genre"];

year = Request.Form["year"];

}

}

前几行创建变量(title、genre和 year)以保存文本框中的值。The first few lines create variables (title, genre, and year) to hold the values from the text boxes. 行 if(IsPost) 确保只在用户单击 "添加电影" 按钮时(即,在窗体已发布后)设置变量。The line if(IsPost) makes sure that the variables are set only when users click the Add Movie button — that is, when the form has been posted.

正如你在前面的教程中看到的那样,可以使用表达式(如 Request.Form["name"])获取文本框的值,其中name是 元素的名称。As you saw in an earlier tutorial, you get the value of a text box by using an expression like Request.Form["name"], where name is the name of the element.

变量(title、genre和 year)的名称是任意的。The names of the variables (title, genre, and year) are arbitrary. 与分配给 元素的名称类似,你可以随意调用它们。Like the names that you assign to elements, you can call them anything you like. (变量的名称不必与窗体上 元素的名称属性匹配。)但与 元素一样,可以使用反映它们所包含的数据的变量名称。(The names of the variables don't have to match the name attributes of elements on the form.) But as with the elements, it's a good idea to use variable names that reflect the data that they contain. 编写代码时,一致的名称使你可以更轻松地记住正在处理的数据。When you write code, consistent names make it easier for you to remember what data you're working with.

向数据库添加数据Adding Data to the Database

在刚刚添加的代码块中,只需在 if 块的右大括号(})内(而不是在代码块内),添加以下代码:In the code block you just added, just inside the closing brace ( } ) of the if block (not just inside the code block), add the following code:

var db = Database.Open("WebPagesMovies");

var insertCommand = "INSERT INTO Movies (Title, Genre, Year) VALUES(@0, @1, @2)";

db.Execute(insertCommand, title, genre, year);

此示例类似于在上一教程中用于提取和显示数据的代码。This example is similar to the code you used in a previous tutorial to fetch and display data. 以 db = 开头的行将打开数据库(与之前一样),下一行将再次定义 SQL 语句,如之前所见。The line that starts with db = opens the database, like before, and the next line defines a SQL statement, again as you saw before. 但这次它定义了 SQL Insert Into 语句。However, this time it defines a SQL Insert Into statement. 下面的示例显示了 Insert Into 语句的常规语法:The following example shows the general syntax of the Insert Into statement:

INSERT INTO table (column1, column2, column3, ...) VALUES (value1, value2, value3, ...)

换句话说,您可以指定要插入的表,然后列出要插入的列,然后列出要插入的值。In other words, you specify the table to insert into, then list the columns to insert into, and then list the values to insert. (如前所述,SQL 不区分大小写,但有些人会将关键字改为大写,以便更轻松地读取命令。)(As noted before, SQL is not case sensitive but some people capitalize the keywords to make it easier to read the command.)

要插入的列已在命令中列出,(Title, Genre, Year)。The columns that you're inserting into are already listed in the command — (Title, Genre, Year). 有趣的部分是如何将文本框中的值获取到命令的 VALUES 部分。The interesting part is how you get the values from the text boxes into the VALUES part of the command. 您看到的是 @0、@1和 @2,而不是实际值。Instead of actual values, you see @0, @1, and @2, which are of course placeholders. 运行命令时(在 "db.Execute" 行中),将从文本框中传递所获得的值。When you run the command (on the db.Execute line), you pass the values that you got from the text boxes.

重要提示!Important! 请记住,你只应在 SQL 语句中包括用户在线输入的数据的唯一方法是使用占位符,如此处所示(VALUES(@0, @1, @2))。Remember that the only way you should ever include data entered online by a user in a SQL statement is to use placeholders, as you see here (VALUES(@0, @1, @2)). 如果将用户输入连接到 SQL 语句,会自行打开 SQL 注入式攻击,如 ASP.NET 网页(上一教程)中的窗体基础中所述。If you concatenate user input into a SQL statement, you open yourself to a SQL injection attack, as explained in Form Basics in ASP.NET Web Pages (the previous tutorial).

在 if 块中,在 db.Execute 行后面添加以下行:Still inside the if block, add the following line after the db.Execute line:

Response.Redirect("~/Movies");

将新电影插入到数据库后,此线将跳转到 "电影" 页,以便您可以看到刚刚输入的影片。After the new movie has been inserted into the database, this line jumps you (redirects) to the Movies page so you can see the movie you just entered. ~ 运算符表示 "网站的根"。The ~ operator means "root of the website." (~ 运算符仅适用于 ASP.NET 页面,而不能在 HTML 中使用。)(The ~ operator works only in ASP.NET pages, not in HTML generally.)

完整的代码块如下例所示:The complete code block looks like this example:

@{

var title = "";

var genre = "";

var year = "";

if(IsPost){

title = Request.Form["title"];

genre = Request.Form["genre"];

year = Request.Form["year"];

var db = Database.Open("WebPagesMovies");

var insertCommand = "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)";

db.Execute(insertCommand, title, genre, year);

Response.Redirect("~/Movies");

}

}

测试插入命令(迄今为止)Testing the Insert Command (So Far)

尚未完成,但现在是一个好的测试时间。You're not done yet, but now is a good time to test.

在 WebMatrix 中文件的树状视图中,右键单击 " AddMovie " 页,然后单击 "在浏览器中启动"。In the tree view of files in WebMatrix, right-click the AddMovie.cshtml page and then click Launch in browser.

60f15b440ad3365da9b3a1a321676158.png

(如果你在浏览器中结束了不同的页面,请确保 URL http://localhost:nnnnn/AddMovie),其中nnnnn是你正在使用的端口号。)(If you end up with a different page in the browser, make sure that the URL is http://localhost:nnnnn/AddMovie), where nnnnn is the port number that you're using.)

您是否收到错误页?Did you get an error page? 如果是这样,请仔细阅读并确保代码看起来与前面列出的内容完全相同。If so, read it carefully and make sure that the code looks exactly what was listed earlier.

以格式输入电影 — 例如,使用 "公民 Kane"、"Drama" 和 "1941"。Enter a movie in the form — for example, use "Citizen Kane", "Drama", and "1941". (或任何其他内容)然后单击 "添加电影"。(Or whatever.) Then click Add Movie.

如果一切顺利,您会被重定向到电影页面。If all goes well, you're redirected to the Movies page. 请确保您的新电影已列出。Make sure that your new movie is listed.

8a553f68054376f5dd399774f5c6ba03.png

验证用户输入Validating User Input

返回到AddMovie页,或再次运行它。Go back to the AddMovie page, or run it again. 输入其他电影,但这次仅输入标题 — 例如,输入 "Singin' in Rain"。Enter another movie, but this time, enter only the title — for example, enter "Singin' in the Rain". 然后单击 "添加电影"。Then click Add Movie.

你将再次重定向到电影页面。You're redirected to the Movies page again. 您可以找到新电影,但它不完整。You can find the new movie, but it's incomplete.

ae4c378d80f155c20999dbf81cf1f4e5.png

当您创建了电影表时,您显式地说没有任何字段可以为 null。When you created the Movies table, you explicitly said that none of the fields could be null. 这里有一个新电影的输入窗体,并将字段留空。Here you have an entry form for new movies, and you're leaving fields blank. 这是个错误。That's an error.

在这种情况下,数据库不会实际引发(或引发)错误。In this case, the database didn't actually raise (or throw) an error. 你未提供流派或年份,因此AddMovie页中的代码将这些值视为所谓的空字符串。You didn't supply a genre or year, so the code in the AddMovie page treated those values as so-called empty strings. 当 SQL Insert Into 命令运行时,"流派" 和 "年份" 字段在其中没有有用的数据,但是它们不是 null。When the SQL Insert Into command ran, the genre and year fields didn't have useful data in them, but they weren't null.

很显然,您不想让用户在数据库中输入半空电影信息。Obviously, you don't want to let users enter half-empty movie information into the database. 解决方案是验证用户的输入。The solution is to validate the user's input. 最初,验证只需确保用户输入了所有字段的值(即,它们都不包含空字符串)。Initially, the validation will simply make sure that the user has entered a value for all of the fields (that is, that none of them contains an empty string).

Tip

Null 和空字符串Null and Empty Strings

在编程中,"无值" 的不同概念之间存在差异。In programming, there's a distinction between different notions of "no value." 通常,如果从未以任何方式对其进行设置或初始化,则该值为null 。In general, a value is null if it has never been set or initialized in any way. 相反,需要字符数据(字符串)的变量可以设置为空字符串。In contrast, a variable that expects character data (strings) can be set to an empty string. 在这种情况下,值不为 null;它只是显式设置为长度为零的字符字符串。In that case, the value is not null; it's just been explicitly set to a string of characters whose length is zero. 这两个语句显示了差异:These two statements show the difference:

var firstName;   // Not set, so its value is null

var firstName = ""; // Explicitly set to an empty string -- not null

这有点复杂,但要点是 null 表示一种不确定的状态。It's a little more complicated than that, but the important point is that null represents a sort of undetermined state.

现在,必须准确了解某个值为 null 时,以及何时只是一个空字符串。Now and then it's important to understand exactly when a value is null and when it's just an empty string. 在AddMovie页的代码中,可以使用 Request.Form["title"] 等来获取文本框的值。In the code for the AddMovie page, you get the values of the text boxes by using Request.Form["title"] and so on. 首次运行页面时(在单击按钮之前),Request.Form["title"] 的值为 null。When the page first runs (before you click the button), the value of Request.Form["title"] is null. 但在提交窗体时,Request.Form["title"] 获取 title 文本框的值。But when you submit the form, Request.Form["title"] gets the value of the title text box. 这并不明显,但空文本框不是 null;它中只包含一个空字符串。It's not obvious, but an empty text box is not null; it just has an empty string in it. 因此,当运行代码以响应按钮单击时,Request.Form["title"] 在其中包含空字符串。So when the code runs in response to the button click, Request.Form["title"] has an empty string in it.

为什么此项区分非常重要?Why is this distinction important? 当您创建了电影表时,您显式地说没有任何字段可以为 null。When you created the Movies table, you explicitly said that none of the fields could be null. 但这里有一个新电影的输入窗体,而您会将字段留空。But here you have an entry form for new movies, and you're leaving fields blank. 当您尝试保存没有流派或年份值的新电影时,您可能希望数据库产生抱怨。You would reasonably expect the database to complain when you tried to save new movies that didn't have values for genre or year. 但这也是 — 即使将这些文本框留空也是如此,这些值不是 null;它们是空字符串。But that's the point — even if you leave those text boxes blank, the values aren't null; they're empty strings. 因此,您可以将新电影保存到数据库中,其中,这些列为空 — 但不是 null!As a result, you're able to save new movies to the database with these columns empty — but not null! — 值。— values. 因此,你必须确保用户不会提交空字符串,你可以通过验证用户的输入来完成此操作。Therefore, you have to make sure that users don't submit an empty string, which you can do by validating the user's input.

验证帮助器The Validation Helper

ASP.NET 网页包含了帮助程序 — Validation 的帮助器 —,可用于确保用户输入满足你的要求的数据。ASP.NET Web Pages includes a helper — the Validation helper — that you can use to make sure that users enter data that meets your requirements. Validation 帮助器是内置于 ASP.NET 网页的帮助器之一,因此您无需使用 NuGet 将其作为包安装,这是在前面的教程中安装 Gravatar helper 的方式。The Validation helper is one of the helpers that's built in to ASP.NET Web Pages, so you don't have to install it as a package by using NuGet, the way you installed the Gravatar helper in an earlier tutorial.

若要验证用户的输入,你需要执行以下操作:To validate the user's input, you'll do the following:

使用代码指定希望在页的文本框中需要值。Use code to specify that you want to require values in the text boxes on the page.

将测试放入代码,以便仅当所有内容都得到正确验证时才将电影信息添加到数据库中。Put a test into the code so that the movie information is added to the database only if everything validates properly.

向标记添加代码以显示错误消息。Add code into the markup to display error messages.

在AddMovie页的代码块中,在变量声明之前的顶部,添加以下代码:In the code block in the AddMovie page, right up at the top before the variable declarations, add the following code:

Validation.RequireField("title", "You must enter a title");

Validation.RequireField("genre", "Genre is required");

Validation.RequireField("year", "You haven't entered a year");

对于要在其中需要输入的每个字段( 元素),只需调用一次 Validation.RequireField。You call Validation.RequireField once for each field ( element) where you want to require an entry. 你还可以为每个调用添加自定义错误消息,如下所示。You can also add a custom error message for each call, like you see here. (我们只是为了显示您可以放入您的内容。)(We varied the messages just to show that you can put anything you like there.)

如果出现问题,则需要防止将新的电影信息插入到数据库中。If there's a problem, you want to prevent the new movie information from being inserted into the database. 在 if(IsPost) 块中,使用 && (逻辑 AND)添加另一个测试 Validation.IsValid()的条件。In the if(IsPost) block, use && (logical AND) to add another condition that tests Validation.IsValid(). 完成后,整个 if(IsPost) 块如下所示:When you're done, the whole if(IsPost) block looks like this code:

if(IsPost && Validation.IsValid()){

title = Request.Form["title"];

genre = Request.Form["genre"];

year = Request.Form["year"];

var db = Database.Open("WebPagesMovies");

var insertCommand = "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)";

db.Execute(insertCommand, title, genre, year);

Response.Redirect("~/Movies");

}

如果使用 Validation 帮助程序注册的任何字段存在验证错误,则 Validation.IsValid 方法返回 false。If there's a validation error with any of the fields that you registered by using the Validation helper, the Validation.IsValid method returns false. 在这种情况下,该块中的任何代码都不会运行,因此不会在数据库中插入无效的电影条目。And in that case, none of the code in that block will run, so no invalid movie entries will be inserted into the database. 当然,您不会重定向到电影页面。And of course you're not redirected to the Movies page.

完整的代码块,包括验证代码,现在如下例所示:The complete code block, including the validation code, now looks like this example:

@{

Validation.RequireField("title", "You must enter a title");

Validation.RequireField("genre", "Genre is required");

Validation.RequireField("year", "You haven't entered a year");

var title = "";

var genre = "";

var year = "";

if(IsPost && Validation.IsValid()){

title = Request.Form["title"];

genre = Request.Form["genre"];

year = Request.Form["year"];

var db = Database.Open("WebPagesMovies");

var insertCommand = "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)";

db.Execute(insertCommand, title, genre, year);

Response.Redirect("~/Movies");

}

}

显示验证错误Displaying Validation Errors

最后一步是显示任何错误消息。The last step is to display any error messages. 可以为每个验证错误显示单独的消息,也可以显示摘要或同时显示两者。You can display individual messages for each validation error, or you can display a summary, or both. 在本教程中,您将执行这两项操作,以便您可以看到它的工作原理。For this tutorial, you'll do both so that you can see how it works.

在要验证的每个 元素旁边,调用 Html.ValidationMessage 方法并向其传递要验证的 元素的名称。Next to each element that you're validating, call the Html.ValidationMessage method and pass it the name of the element you're validating. 将 Html.ValidationMessage 方法放在要显示错误消息的位置。You put the Html.ValidationMessage method right where you want the error message to appear. 当页面运行时,Html.ValidationMessage 方法将呈现验证错误将呈现的 元素。When the page runs, the Html.ValidationMessage method renders a element where the validation error will go. (如果没有错误,则会呈现 元素,但其中没有任何文本。)(If there's no error, the element is rendered, but there's no text in it.)

更改页面中的标记,使其包含页面上三个 元素的 Html.ValidationMessage 方法,如以下示例所示:Change the markup in the page so that it includes an Html.ValidationMessage method for each of the three elements on the page, like this example:

Title:

@Html.ValidationMessage("title")

Genre:

@Html.ValidationMessage("genre")

Year:

@Html.ValidationMessage("year")

若要查看摘要的工作原理,还应在页面上的

Add a Movie

元素之后添加以下标记和代码:To see how the summary works, also add the following markup and code right after the

Add a Movie

element on the page:

@Html.ValidationSummary()

默认情况下,Html.ValidationSummary 方法将在列表中显示所有验证消息(在

元素内的
  • 元素)。By default, the Html.ValidationSummary method displays all the validation messages in a list (a
    • element that's inside a
element). 与 Html.ValidationMessage 方法一样,验证摘要的标记始终呈现;如果没有错误,则不会呈现列表项。As with the Html.ValidationMessage method, the markup for the validation summary is always rendered; if there are no errors, no list items are rendered.

摘要可以是显示验证消息的另一种方法,而不是使用 Html.ValidationMessage 方法来显示每个特定于字段的错误。The summary can be an alternative way to display validation messages instead of by using the Html.ValidationMessage method to display each field-specific error. 或者,您可以使用摘要和详细信息。Or you can use both a summary and the details. 或者,您可以使用 Html.ValidationSummary 方法来显示一般错误,然后使用各个 Html.ValidationMessage 调用来显示详细信息。Or you can use the Html.ValidationSummary method to display a generic error and then use individual Html.ValidationMessage calls to display details.

完整的页现在如下例所示:The complete page now looks like this example:

@{

Validation.RequireField("title", "You must enter a title");

Validation.RequireField("genre", "Genre is required");

Validation.RequireField("year", "You haven't entered a year");

var title = "";

var genre = "";

var year = "";

if(IsPost && Validation.IsValid()){

title = Request.Form["title"];

genre = Request.Form["genre"];

year = Request.Form["year"];

var db = Database.Open("WebPagesMovies");

var insertCommand = "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)";

db.Execute(insertCommand, title, genre, year);

Response.Redirect("~/Movies");

}

}

Add a Movie

Add a Movie

@Html.ValidationSummary()

Movie Information

Title:

@Html.ValidationMessage("title")

Genre:

@Html.ValidationMessage("genre")

Year:

@Html.ValidationMessage("year")

介绍完毕。That's it. 现在可以通过添加电影来测试页面,但要保留一个或多个字段。You can now test the page by adding a movie but leaving out one or more of the fields. 当你执行此操作时,将看到以下错误显示:When you do, you see the following error display:

a081f763e90f05a9192c6ded3983e958.png

设置验证错误消息的样式Styling the Validation Error Messages

您可以看到存在错误消息,但它们并不是很好。You can see that there are error messages, but they don't really stand out very well. 不过,有一种简单的方法可以对错误消息进行样式。There's an easy way to style the error messages, though.

若要为 Html.ValidationMessage显示的各个错误消息建立样式,请创建一个名为 field-validation-error的 CSS 样式类。To style the individual error messages that are displayed by Html.ValidationMessage, create a CSS style class named field-validation-error. 若要定义验证摘要的外观,请创建一个名为 validation-summary-errors的 CSS 样式类。To define the look for the validation summary, create a CSS style class named validation-summary-errors.

若要查看此方法的工作方式,请在页面的

部分中添加一个

通常,您可能会将样式信息放在单独的 .css文件中,但为了简单起见,您现在可以将其放在页面中。Normally you'd probably put style information into a separate .css file, but for simplicity you can put them in the page for now. (在本教程的后面部分中,您将 CSS 规则移到单独的 .css文件中。)(Later in this tutorial set, you'll move the CSS rules to a separate .css file.)

如果存在验证错误,Html.ValidationMessage 方法将呈现包含 class="field-validation-error"的 元素。If there's a validation error, the Html.ValidationMessage method renders a element that includes class="field-validation-error". 通过添加该类的样式定义,可以配置消息的外观。By adding a style definition for that class, you can configure what the message looks like. 如果有错误,ValidationSummary 方法同样会动态呈现特性 class="validation-summary-errors"。If there are errors, the ValidationSummary method likewise dynamically renders the attribute class="validation-summary-errors".

再次运行该页,并特意忽略几个字段。Run the page again and deliberately leave out a couple of the fields. 现在,这些错误比较明显。The errors are now more noticeable. (实际上,它们是 overdone 的,但这只是为了显示您可以执行的操作。)(In fact, they're overdone, but that's just to show what you can do.)

b7f3fa9b06a0b666442d0459e6ea545b.png

添加电影页面的链接Adding a Link to the Movies Page

最后一步是让从原始电影列表访问AddMovie页面变得非常方便。One final step is to make it convenient to get to the AddMovie page from the original movie listing.

再次打开电影页面。Open the Movies page again. 在 WebGrid 助手后面的结束

标记后,添加以下标记:After the closing
tag that follows the WebGrid helper, add the following markup:

Add a movie

如前文所述,ASP.NET 会将 ~ 运算符解释为网站的根。As you saw before, ASP.NET interprets the ~ operator as the root of the website. 无需使用 ~ 运算符;您可以使用标记 Add a movie 或其他方式来定义 HTML 理解的路径。You don't have to use the ~ operator; you could use the markup Add a movie or some other way to define the path that HTML understands. 但是,当你为 Razor 页面创建链接时,~ 运算符是一种很好的通用方法,因为它使站点更灵活-如果将当前页移动到子文件夹,则该链接仍将转到AddMovie页。But the ~ operator is a good general approach when you create links for Razor pages, because it makes the site more flexible — if you move the current page to a subfolder, the link will still go to the AddMovie page. (请记住,~ 运算符仅适用于cshtml页。(Remember that the ~ operator only works in .cshtml pages. ASP.NET 理解它,但它不是标准 HTML。)ASP.NET understands it, but it's not standard HTML.)

完成后,运行 "电影" 页。When you're done, run the Movies page. 它将如下所示:It will look like this page:

1c763514b9315b70b0f42e8972bf8740.png

单击 "添加电影" 链接,确保它转到AddMovie页。Click the Add a movie link to make sure that it goes to the AddMovie page.

下一步Coming Up Next

在下一教程中,您将学习如何允许用户编辑数据库中已有的数据。In the next tutorial, you'll learn how to let users edit data that's already in the database.

AddMovie 页的完整列表Complete Listing for AddMovie Page

@{

Validation.RequireField("title", "You must enter a title");

Validation.RequireField("genre", "Genre is required");

Validation.RequireField("year", "You haven't entered a year");

var title = "";

var genre = "";

var year = "";

if(IsPost && Validation.IsValid()){

title = Request.Form["title"];

genre = Request.Form["genre"];

year = Request.Form["year"];

var db = Database.Open("WebPagesMovies");

var insertCommand = "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)";

db.Execute(insertCommand, title, genre, year);

Response.Redirect("~/Movies");

}

}

Add a Movie

.field-validation-error {

font-weight:bold;

color:red;

background-color:yellow;

}

.validation-summary-errors{

border:2px dashed red;

color:red;

background-color:yellow;

font-weight:bold;

margin:12px;

}

Add a Movie

@Html.ValidationSummary()

Movie Information

Title:

@Html.ValidationMessage("title")

Genre:

@Html.ValidationMessage("genre")

Year:

@Html.ValidationMessage("year")

其他资源Additional Resources

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现用Java在网页输入数据并存储到数据库,可以分为以下几个步骤: 1. 编写前端页面:可以使用HTML、CSS和JavaScript等技术编写一个简单的表单页面,包含输入框和提交按钮。 2. 使用Java Servlet处理提交请求:使用Java Servlet技术监听并处理前端页面的提交请求,获取前端页面中的输入数据。 3. 连接数据库使用Java JDBC技术连接关系型数据库,例如MySQL、Oracle等。 4. 编写SQL语句:使用SQL语句将获取的数据插入到数据库中。 5. 执行SQL语句:使用Java JDBC技术执行SQL语句,将数据插入到数据库中。 下面是一个简单的示例代码,用于将前端页面中的数据存储到MySQL数据库中: ```java // 获取前端页面中的数据 String name = request.getParameter("name"); String age = request.getParameter("age"); String address = request.getParameter("address"); // 连接数据库 Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password"); // 编写SQL语句 String sql = "INSERT INTO user(name, age, address) VALUES(?, ?, ?)"; // 执行SQL语句 PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, age); pstmt.setString(3, address); pstmt.executeUpdate(); // 关闭数据库连接 pstmt.close(); conn.close(); ``` 注意:以上示例代码仅供参考,具实现方式还需要根据具的需求进行调整。

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值