ASP.NET MVC 3 (Adding Validation to the Model) (7/9)
2011-01-22 18:03
597 查看
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 theMovieclass.
Open the
Movieclass file. We'll add attributes from the System.ComponentModel.DataAnnotations namespace, so you need to add a
usingstatement for
System.ComponentModel.DataAnnotations. We'll apply the Required attribute and the Range attribute. The
Requiredattribute makes a field required; in the sample, the user will have to enter a title. The
Rangeattribute constrains the field within the specified range.
The following code shows the
Movieclass 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:
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.
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
Movieclass. 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.
相关文章推荐
- ASP.NET MVC 3 (Adding Validation to the Model) (7/9)
- ASP.NET MVC 3 (Adding a New Field to the Movie Model and Table) (8/9)
- ASP.NET MVC 3 (Adding a New Field to the Movie Model and Table) (8/9)
- (转)How to use the ASP.NET MVC ModelBinder
- Extending the ASP.Net Security model to use rights
- How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
- How to get all Errors from ASP.Net MVC modelState?
- 【引】How to Choose the Best Way to Pass Multiple Models in ASP.NET MVC
- HTML5, jQuery Mobile and ASP.NET MVC 4 – Using the ViewModel between the model and controller
- 解决ASP.NET MVC(post数据)Json请求太大,无法反序列化(The JSON request was too large to be deserialized)
- ASP.NET MVC - how to make users confirm the delete
- Introduction to ASP.NET's Model View Controller (MVC) Design Pattern
- Asp.net MVC 出现“Failed to map the path '/'.”错误
- ASP.NET MVC- Model- An Introduction to Entity Framework for Absolute Beginners
- ASP.NET MVC Toolkit - how to use the Html Helper class
- How to get the Current Controller Name, Action, or ID in ASP.NET MVC
- Model Validation in Asp.net MVC
- ASP.NET Error:Adding the specified count to the semaphore would cause it to exceed its maximum count
- Model Validation in Asp.net MVC
- Asp.Net Mvc: Model Binding to Simple Types, Complex Types, Collections, Dictionaries, Etc