ASP.NET MVC 入門介紹 (下)

來源:互聯網
上載者:User

我們來完善驗證功能。在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; }
}

  再運行下程式,就可以看到效果:

  當然,預設的驗證往往並不足夠,可以嘗試下將日期改為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);
}
}
}

  主要實現IsValid方法,如有需要也可以實現FormatErrorMessage方法。要注意屬性的參數只能是有限的幾種類型,參考這裡。寫好以後,把HelloWorld項目添加Biz.Web引用,然後就可以使用了,例如:

[Display(Name="發布日期"),Date(MaxDate="2012-01-01",ErrorMessage="2012地球滅亡啦")]
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());
}

  在View頁面,添加一個Form,裡面放上一個選擇框和一個按鈕,代碼如下:

@using (Html.BeginForm("Index", "Movie", FormMethod.Get))
{
<p>Genre: @Html.DropDownList("MovieGenre","全部") <input type="submit" value="篩選"/></p>
}

  效果如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.