ASP.NET MVC 3 (Adding Validation to the Model) (7/9)

來源:互聯網
上載者:User
文章目錄
  • Adding Validation to the Model
Adding Validation to the Model

In this section we're going to implement the support necessary to enable input validation in the application. We'll ensure that database content is correct and provide helpful error messages to end users when they try to enter movie data that isn't valid. We'll begin by adding a little validation logic to the Movie class.

Open the Movie class file. We'll add attributes from the System.ComponentModel.DataAnnotations namespace, so you need to add a using statement for System.ComponentModel.DataAnnotations. We'll apply the Required attribute and the Range attribute. The Required attribute makes a field required; in the sample, the user will have to enter a title. The Range attribute constrains the field within the specified range.

The following code shows the Movie class with these two attributes applied.

 public class Movie  {     public int ID { get; set; }      [Required]     public string Title { get; set; }      public DateTime ReleaseDate { get; set; }      public string Genre { get; set; }      [Required]     [Range(5, 100, ErrorMessage = "The price must be between $5 and $100")]     public decimal Price { get; set; }  }

The attributes are applied not only to the model; when you use the code-first approach, Entity Framework applies them to the database. Run the application and you see the following error:

The model backing the 'MovieDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance

You're seeing this error because in the code-first approach, Entity Framework automatically created the database, and by default when it creates a database, it adds a table that helps tracks whether the schema of the database is in sync with the model classes. Entity Framework throws an error if they become out of sync, which makes it easier to track down issues sat development time that you might otherwise find (by obscure errors) only at run time.

There are two basic approaches to solving this problem:

  1. Have Entity Framework automatically re-create the database based on the new model class schema. The downside of this approach is that you lose all existing data.
  2. Modify the schema of the existing database to sync it with the model classes. The advantage of this approach is that you keep your data. The disadvantage is that you have to make the same change in two places (in your model and in the database schema).

For this tutorial, we'll delete the database. A new one that includes our changes will be automatically created the next time we run the application. To delete the movies database, we'll use SQL Management Studio Express 2008.  if you don't already have this free database utility, you can use the Web Platform Installer to download and install it.

Start SQL Server Management Studio.

The Connect to Server dialog box is displayed.

In the Server name box, enter the following name:

./SQLEXPRESS


Click Connect. The Movies database is displayed in the Object Explorer pane on the left.

Right-click the Movies database and select Delete.

(If you've got data that you want to save, you can export it from the Movies database using SQL Management Studio before you delete the database.)

In the Delete dialog box, make sure the Close existing connections check box is selected, then click OK. The Movies database is now deleted.

Run the application. A new database is created that includes the recent changes to the Movie class. In the browser, navigate to /Movies/Create and try to create a new movie with a price outside the specified range.

The price range error is displayed as soon as you tab out of the price field, before you submit the form. The client-side validation was enabled by the scaffolding mechanism that created the view. Open the Movies/Create.cshtml file. The following two lines enable client-side jQuery validation.

<script src="@Url.Content("/Scripts/jquery.validate.min.js")"  type="text/javascript"></script>  <script  src="@Url.Content("/Scripts/jquery.validate.unobtrusive.min.js")"  type="text/javascript"></script>

This is looking good! We've got client validation to immediately notify users if the data they entered is not valid. Next, let's add a new column to the database.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.