1.在Model類里面添加驗證,代碼如下:
1 public class Movie 2 { 3 public int ID { get; set; } 4 [StringLength(60,MinimumLength=3,ErrorMessage="主題的長度必須在3到60個字符")] 5 public string Title { get; set; } 6 7 [Display(Name="Release Date")] 8 [DataType(DataType.Date)] 9 [DisplayFormat(DataFormatString="{0:yyyy-MM-dd}",ApplyFormatInEditMode=true)]10 public DateTime ReleaseDate { get; set; }11 [RegularEx1 The StringLength attribute sets the maximum length of the string, and it sets this limitation on the database, therefore the database schema will change. Right click on the Movies table in Server explorer and click Open Table Definition:2 3 這個StringLength屬性,設置了最大的字符串長度,限制了數據庫,所以數據庫結構會改變。我們先來看看數據庫結構沒改變之前的定義是咋樣的:2.請看圖:
3.
1 In the image above, you can see all the string fields are set to NVARCHAR (MAX). We will use migrations to update the schema. Build the solution, and then open the Package Manager Console window and enter the following commands: 2 3 add-migration DataAnnotations 4 update-database 5 6 When this command finishes, Visual Studio opens the class file that defines the new DbMIgration derived class with the name specified (DataAnnotations), and in the Up method you can see the code that updates the schema constraints: 7 8 9 在上面的圖片中,你看到,所有的string類型的字段,都是NVARCHAR (MAX),我們將會使用數據庫遷移技術,來更新表結構,打開程序包管理器控制臺,輸入下面的指令:10 add-migration DataAnnotations11 update-database12 13 當這個指令結束之后,VS打開生成的遷移文件,在Up方法中,你看到了添加的數據庫約束:4.請看圖片:
5.下面,我們再來打開數據庫,看下數據表結構發生了什么變化:
6.
1 The validation attributes specify behavior that you want to enforce on the model properties they are applied to. The Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit what characters can be input. In the code above, Genre and Rating must use only letters (white space, numbers and special characters are not allowed). The Range attribute constrains a value to within a specified range. The StringLength attribute lets you set the maximum length of a string property, and optionally its minimum length. Value types (such as decimal, int, float, DateTime) are inherently required and don't need the Required attribute.2 這個驗證屬性指定了你想要應用到Model中的屬性。Required和MinimumLength屬性,表明:必須要有一個值,但是不會阻止用戶輸入一個空格來滿足這個驗證。RegularExpression屬性,用來限制,什么字符可以被輸入,在上面的代碼中Genre和Rating字段必須只能是字母,(空格,數字還有其他的特殊字符都是不被允許的。),Range屬性約束了一個值必須在某個特定的范圍之內,StringLength屬性讓你可以設置,字符串的最大長度,值類型(例如;decilmal,int float,DateTime)都是內在需要的,然而對于Required來說,則并不需要。3 4 Code First ensures that the validation rules you specify on a model class are enforced before the application saves changes in the database. For example, the code below will throw a DbEntityValidationException exception when the SaveChanges method is called, because several required Movie property values are missing:5 6 Code First 確保你指定在Model中的驗證,在數據庫數據保存前,能夠被驗證。例如下面的代碼,當SaveChanges調用的時候,將會拋出一個錯誤,因為有一些必須要的字段丟失了。1 MovieDBContext db = new MovieDBContext();2 Movie movie = new Movie();3 movie.Title = "Gone with the Wind";4 db.Movies.Add(movie);5 db.SaveChanges(); // <= Will throw server side validation exception7.
1 Having validation rules automatically enforced by the .NET Framework helps make your application more robust. It also ensures that you can't forget to validate something and inadvertently let bad data into the database.2 3 數據驗證,通過 .NET Framework 自動的被執行,這可以使你的程序更健壯,同樣它會確保你,不會忘記去驗證一些,還有不是故意的要讓不好的數據更新到數據庫中。8。下面我們開始驗證吧,運行項目;
1 Click the Create New link to add a new movie. Fill out the form with some invalid values. As soon as jQuery client side validation detects the error, it displays an error message.2 3 點擊這個新建的鏈接,去添加一個新的movie。輸入不合法的數據,然后就看到錯誤了。
1 Note to support jQuery validation for non-English locales that use a comma (",") for a decimal point, you must include the NuGet globalize as described previously in this tutorial.9.
Notice how the form has automatically used a red border color to highlight the text boxes that contain invalid data and has emitted an appropriate validation error message next to each one. The errors are enforced both client-side (using javaScript and jQuery) and server-side (in case a user has Javascript disabled).注意到:表單自動的使用了一個紅色的邊框來高亮顯示要驗證的文本框里面的錯誤數據。錯誤消息就顯示在旁邊。(PS:這里我節省時間,就隨便大概翻譯一下了,只是把大概的意思翻出來。)A real benefit is that you didn't need to change a single line of code in the MoviesController class or in the Create.cshtml view in order to enable this validation UI. The controller and views you created earlier in this tutorial automatically picked up the validation rules that you specified by using validation attributes on the properties of the Movie model class. Test validation using the Edit action method, and the same validation is applied.這個真正的好處是,你不必為了可以使用validation UI,而在控制器,或者在視圖頁面中去改變代碼,控制器和視圖頁面,捕獲了你在前面的Model類里面寫的驗證規則。測試驗證,我們使用編輯方法,這個驗證同樣適用于編輯的功能。The form data is not sent to the server until there are no client side validation errors. You can verify this by putting a break point in the HTTP Post method, by using the fiddler tool, or the IE F12 developer tools.表單的數據,不會提交到服務器,除非沒有客戶端錯誤的驗證機制。你可以在瀏覽器中按F12,并在Post方法中,設置斷點來調試。10.驗證是怎樣出現在視圖和方法里面的呢:
You might wonder how the validation UI was generated without any updates to the code in the controller or views. The next listing shows what the Create methods in the MovieController class look like. They're unchanged from how you created them earlier in this tutorial.你可能想到的是這個界面的驗證是怎樣在沒有修改控制器和視圖的情況下產生的呢。下面的代碼,是控制器的代碼,你之前創建的,沒有任何修改的1 public ActionResult Create() 2 { 3 return View(); 4 } 5 // POST: /Movies/Create 6 // To protect from overposting attacks, please enable the specific properties you want to bind to, for 7 // more details see http://go.microsoft.com/fwlink/?LinkId=317598. 8 [HttpPost] 9 [ValidateAntiForgeryToken]10 public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price,Rating")] Movie movie)11 {12 if (ModelState.IsValid)13 {14 db.Movies.Add(movie);15 db.SaveChanges();16 return RedirectToAction("Index");17 }18 return View(movie);19 }1 The first (HTTP GET) Create action method displays the initial Create form. The second ([HttpPost]) version handles the form post. The second Create method (The HttpPost version) calls ModelState.IsValid to check whether the movie has any validation errors. Calling this method evaluates any validation attributes that have been applied to the object. If the object has validation errors, the Create method re-displays the form. If there are no errors, the method saves the new movie in the database. In our movie example, the form is not posted to the server when there are validation errors detected on the client side; the second Create method is never called. If you disable JavaScript in your browser, client validation is disabled and the HTTP POST Create method calls ModelState.IsValid to check whether the movie has any validation errors.2 3 第一個Create方法(HTTP GET)展示初始的數據,第二個Create方法,處理表單的提交。第二個create方法,調用這個ModelState.IsValid 來檢查movie實體中是否有驗證不通過的數據。通過調用ModelState.IsValid可以來判斷是否有驗證屬性,作用在某個對象上面。如果這個對象出現驗證錯誤,這個Create方法,再次展示表單,如果沒有錯誤,就將數據保存到數據庫中。在我們的例子中,當客戶端驗證出現錯誤了,表單的數據是
新聞熱點
疑難解答