᳓前言
本篇文章將"Adding Validation"整理而成。᳓重點整理
- 在Model類別中加入驗證邏輯,如此一來,在這個應用程式中對於該Model的所有新增、修改都會依照該邏輯進行驗證。
- ASP.NET MVC的其中一個核心設計概念為DRY(Don't Repeat Yourself),意思是只需要指定功能或行為一次之後,在應用程式中有使用到的各部分就能夠體現出來。好處是能夠減少需要撰寫的程式碼,而且可以有效降低錯誤發生並方便維護。
首先要確認目前資料表的欄位,之後才能做比較。
開啟伺服器管理員->展開資料連接->展開Movies.mdf->右鍵dbo.Movies->選擇開啟資料表定義 |
尚未修改的dbo.Movies |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.ComponentModel.DataAnnotations; // Display | |
using System.Data.Entity; // DbContext | |
using System.Linq; | |
using System.Web; | |
namespace WebApplication1.Models | |
{ | |
public class Movie | |
{ | |
public int ID { get; set; } | |
[StringLength(60, MinimumLength = 3)] | |
public string Title { get; set; } | |
[Display(Name = "Rease Date")] | |
[DataType(DataType.Date)] | |
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] | |
//[DisplayFormat(DataFormatString = "0:d", ApplyFormatInEditMode = true)] | |
public DateTime ReleaseDate { get; set; } | |
[RegularExpression(@"^[A-Z]=[a-zA-Z'\s]*$")] | |
[Required] | |
[StringLength(30)] | |
public string Genre { get; set; } | |
[Range(1, 100)] | |
[DataType(DataType.Currency)] | |
public decimal Price { get; set; } | |
[RegularExpression(@"^[A-Z]=[a-zA-Z'\s]*$")] | |
[StringLength(5)] | |
public string Rating { get; set; } | |
} | |
public class MovieDBContext : DbContext | |
{ | |
public DbSet<Movie> Movies { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace WebApplication1.Migrations | |
{ | |
using System; | |
using System.Data.Entity.Migrations; | |
public partial class AddDataAnnotations : DbMigration | |
{ | |
public override void Up() | |
{ | |
AlterColumn("dbo.Movies", "Title", c => c.String(maxLength: 60)); | |
AlterColumn("dbo.Movies", "Genre", c => c.String(nullable: false, maxLength: 30)); | |
AlterColumn("dbo.Movies", "Rating", c => c.String(maxLength: 5)); | |
} | |
public override void Down() | |
{ | |
AlterColumn("dbo.Movies", "Rating", c => c.String()); | |
AlterColumn("dbo.Movies", "Genre", c => c.String()); | |
AlterColumn("dbo.Movies", "Title", c => c.String()); | |
} | |
} | |
} |
修改後的dbo.Movies(StringLength:設定字串長度、Display:設定欄位顯示名稱、DataType:設定提示View如何顯示特定的資料、DisplayFormat:指定資料顯示的格式、Required:設定是否為必填項目、Range:設定值域、RegularExpression:設定輸入規則,可防止輸入空格、數字、特殊符號等) |
沒有留言:
張貼留言