ASP.NET MVC 入門介紹 (下)
相關文章:ASP.NET MVC 入門介紹 (上)
接上文,我們來完善驗證功能。在System.ComponentModel.DataAnnotations命名空間中,已經有了一些基本的屬性類來實現驗證功能,只要把這些屬性加到Model的字段上就可以了。具體的屬性類可以查MSDN, 下面給出一個例子:
{
[Key,DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[StringLength(10,MinimumLength=2,ErrorMessage="必須是2~10個字符長"),Required,Display(Name="名稱")]
public string Title { get; set; }
[Display(Name="發布日期")]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Range(1,100,ErrorMessage="必須是1~100")]
public decimal Price { get; set; }
public string Rating { get; set; }
}
再運行下程序,就可以看到效果:
當然,默認的驗證往往并不足夠,可以嘗試下將日期改為201-01-1,點擊Create,就會引發異常。我們可以增加自定義的驗證屬性來滿足驗證要求。下面我們來實現一個DateAttribute屬性來實現日期格式和日期范圍的檢查。新建一個動態鏈接庫Biz.Web,添加System.ComponentModel.DataAnnotations引用,新建一個類如下:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlClient;
namespace Biz.Web
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class 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();
}
public string MinDate
{
get;
set;
}
public string MaxDate
{
get;
set;
}
private DateTime minDate, maxDate;
//indicate if the format of the input is really a datetime
private bool isFormatError=true;
public override bool IsValid(object value)
{
//ignore it if no value
if (value == null || string.IsNullOrEmpty(value.ToString()))
return true;
//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;
}
public override string FormatErrorMessage(string name)
{
if (isFormatError)
return "請輸入合法的日期";
return base.FormatErrorMessage(name);
}
}
}
主要實現IsValid方法,如有需要也可以實現FormatErrorMessage方法。要注意屬性的參數只能是有限的幾種類型,參考這里。寫好以后,把HelloWorld項目添加Biz.Web引用,然后就可以使用了,例如:
public DateTime ReleaseDate { get; set; }
看下效果:
當然,這種方式有許多限制,主要是屬性參數的限制,只能是基本類型,而且只能是常量。更復雜的驗證規則的添加請看這里:
Implement Remote Validation in ASP.NET MVC.
下面為lndex頁面加上一些篩選功能。通過給Index傳遞參數來實現篩選,在頁面添加一個selectbox來篩選Genre字段,把MovieController的方法改成:
{
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,里面放上一個選擇框和一個按鈕,代碼如下:
{
<p>Genre: @Html.DropDownList("MovieGenre","全部") <input type="submit" value="篩選" /></p>
}
效果如下: