Validation
@{
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");
}
}
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8"/>
<title>Add a Movie</title>
<styletype="text/css">
.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;
}
</style>
</head>
<body>
<h1>Add a Movie</h1>
@Html.ValidationSummary()
<formmethod="post">
<fieldset>
<legend>Movie Information</legend>
<p><labelfor="title">Title:</label>
<inputtype="text"name="title"value="@Request.Form["title"]"/>
@Html.ValidationMessage("title")
</p>
<p><labelfor="genre">Genre:</label>
<inputtype="text"name="genre"value="@Request.Form["genre"]"/>
@Html.ValidationMessage("genre")
</p>
<p><labelfor="year">Year:</label>
<inputtype="text"name="year"value="@Request.Form["year"]"/>
@Html.ValidationMessage("year")
</p>
<p><inputtype="submit"name="buttonSubmit"value="Add Movie"/></p>
</fieldset>
</form>
</body>
</html>
1.设置表单元素必填
Validation.RequireField("title", "You must enter a title");
2.显示ERRO
@Html.ValidationMessage("title")
3.显示所有ERRO
@Html.ValidationSummary()
4.判断是否验证通过
if(Validation.IsValid()) { world="posted"; }
5.erro 样式定义
<styletype="text/css">
.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;
}
</style>
6.手动添加验证信息
Validation.AddFormError("No movie was selected.");
@{
var title = "";
var genre = "";
var year = "";
var movieId = "";
if(!IsPost){
if(!Request.QueryString["ID"].IsEmpty()){
movieId = Request.QueryString["ID"];
var db = Database.Open("WebPagesMovies");
var dbCommand = "SELECT * FROM Movies WHERE ID = @0";
var row = db.QuerySingle(dbCommand, movieId);
title = row.Title;
genre = row.Genre;
year = row.Year;
}
else{
Validation.AddFormError("No movie was selected.");
// If you are using a version of ASP.NET Web Pages 2 that's
// earlier than the RC release, comment out the preceding
// statement and uncomment the following one.
//ModelState.AddFormError("No movie was selected.");
}
}
}