ASP.NET MVC 入门介绍 (下)
我们来完善验证功能。在System.ComponentModel.DataAnnotations命名空间中,已经有了一些基本的属性类来实现验证功能,只要把这些属性加到Model的字段上就可以了。具体的属性类可以查MSDN, 下面给出一个例子:
publicclass Movie
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
publicint ID { get; set; }
[StringLength(10,MinimumLength=2,ErrorMessage="必须是2~10个字符长"),Required,Display(Name="名称")]
publicstring Title { get; set; }
[Display(Name="发布日期")]
public DateTime ReleaseDate { get; set; }
publicstring Genre { get; set; }
[Range(1,100,ErrorMessage="必须是1~100")]
publicdecimal Price { get; set; }
publicstring Rating { get; set; }
}
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
publicint ID { get; set; }
[StringLength(10,MinimumLength=2,ErrorMessage="必须是2~10个字符长"),Required,Display(Name="名称")]
publicstring Title { get; set; }
[Display(Name="发布日期")]
public DateTime ReleaseDate { get; set; }
publicstring Genre { get; set; }
[Range(1,100,ErrorMessage="必须是1~100")]
publicdecimal Price { get; set; }
publicstring Rating { get; set; }
}
再运行下程序,就可以看到效果:
当然,默认的验证往往并不足够,可以尝试下将日期改为201-01-1,点击Create,就会引发异常。我们可以增加自定义的验证属性来满足验证要求。下面我们来实现一个DateAttribute属性来实现日期格式和日期范围的检查。新建一个动态链接库Biz.Web,添加System.ComponentModel.DataAnnotations引用,新建一个类如下:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;
namespace Biz.Web
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple =false)]
publicclass DateAttribute:ValidationAttribute
{
public DateAttribute()
{
//set default max and min time according to sqlserver datetime type
MinDate =new DateTime(1753, 1, 1).ToString();
MaxDate =new DateTime(9999, 12, 31).ToString();
}
publicstring MinDate
{
get;
set;
}
publicstring MaxDate
{
get;
set;
}
private DateTime minDate, maxDate;
//indicate if the format of the input is really a datetime
privatebool isFormatError=true;
publicoverridebool IsValid(object value)
{
//ignore it if no value
if (value ==null||string.IsNullOrEmpty(value.ToString()))
returntrue;
//begin check
string s = value.ToString();
minDate = DateTime.Parse(MinDate);
maxDate = DateTime.Parse(MaxDate);
bool result =true;
try
{
DateTime date = DateTime.Parse(s);
isFormatError =false;
if (date > maxDate || date < minDate)
result =false;
}
catch (Exception)
{
result =false;
}
return result;
}
publicoverridestring FormatErrorMessage(string name)
{
if (isFormatError)
return"请输入合法的日期";
returnbase.FormatErrorMessage(name);
}
}
}
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;
namespace Biz.Web
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple =false)]
publicclass DateAttribute:ValidationAttribute
{
public DateAttribute()
{
//set default max and min time according to sqlserver datetime type
MinDate =new DateTime(1753, 1, 1).ToString();
MaxDate =new DateTime(9999, 12, 31).ToString();
}
publicstring MinDate
{
get;
set;
}
publicstring MaxDate
{
get;
set;
}
private DateTime minDate, maxDate;
//indicate if the format of the input is really a datetime
privatebool isFormatError=true;
publicoverridebool IsValid(object value)
{
//ignore it if no value
if (value ==null||string.IsNullOrEmpty(value.ToString()))
returntrue;
//begin check
string s = value.ToString();
minDate = DateTime.Parse(MinDate);
maxDate = DateTime.Parse(MaxDate);
bool result =true;
try
{
DateTime date = DateTime.Parse(s);
isFormatError =false;
if (date > maxDate || date < minDate)
result =false;
}
catch (Exception)
{
result =false;
}
return result;
}
publicoverridestring FormatErrorMessage(string name)
{
if (isFormatError)
return"请输入合法的日期";
returnbase.FormatErrorMessage(name);
}
}
}
主要实现IsValid方法,如有需要也可以实现FormatErrorMessage方法。要注意属性的参数只能是有限的几种类型,参考这里。写好以后,把HelloWorld项目添加Biz.Web引用,然后就可以使用了,例如:
[Display(Name="发布日期"),Date(MaxDate="2012-01-01",ErrorMessage="2012地球灭亡啦")]
public DateTime ReleaseDate { get; set; }
public DateTime ReleaseDate { get; set; }
看下效果:
当然,这种方式有许多限制,主要是属性参数的限制,只能是基本类型,而且只能是常量。更复杂的验证规则的添加请看这里:
Implement Remote Validation in ASP.NET MVC.
下面为lndex页面加上一些筛选功能。通过给Index传递参数来实现筛选,在页面添加一个selectbox来筛选Genre字段,把MovieController的方法改成:
public ViewResult Index(string movieGenre)
{
var genre = (from s in db.Movies
orderby s.Genre
select s.Genre).Distinct();
ViewBag.MovieGenre =new SelectList(genre); //给前台准备下拉列表的数据。
if (!string.IsNullOrEmpty(movieGenre))
{
//筛选
var movies = from s in db.Movies where s.Genre == movieGenre select s;
return View(movies);
}
return View(db.Movies.ToList());
}
{
var genre = (from s in db.Movies
orderby s.Genre
select s.Genre).Distinct();
ViewBag.MovieGenre =new SelectList(genre); //给前台准备下拉列表的数据。
if (!string.IsNullOrEmpty(movieGenre))
{
//筛选
var movies = from s in db.Movies where s.Genre == movieGenre select s;
return View(movies);
}
return View(db.Movies.ToList());
}
在View页面,添加一个Form,里面放上一个选择框和一个按钮,代码如下:
@using (Html.BeginForm("Index", "Movie", FormMethod.Get))
{
<p>Genre: @Html.DropDownList("MovieGenre","全部") <input type="submit" value="筛选"/></p>
}
{
<p>Genre: @Html.DropDownList("MovieGenre","全部") <input type="submit" value="筛选"/></p>
}
效果如下:
经验在于积累----小伟