`
suizhikuo
  • 浏览: 28928 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

 
阅读更多

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.

3681.StartSSMS[3]

The Connect to Server dialog box is displayed.

ConnectToServerDlg

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.

分享到:
评论

相关推荐

    ASP.NET MVC MSDN 文档 CHM

    Walkthrough: Adding ASP.NET AJAX Scripting to an MVC Project Action Filtering in MVC Applications How to: Deploy an ASP.NET MVC Application How to: Add a Custom MVC Test Framework in Visual Studio ASP...

    asp.net mvc

    If you have questions about working with this release, post them to the ASP.NET MVC forum (http://forums.asp.net/1146.aspx), where members of the ASP.NET community are frequently able to provide in...

    Test-Drive ASP.NET MVC

    1 Getting Started with ASP.NET MVC 1.1 How ASP.NET MVC Works 1.2 Installing MVC 1.3 MVC in Five Minutes: Building Quote-O-Matic 2 Test-Driven Development 2.1 TDD Explained 2.2 Test-Driving ...

    ASP.NET MVC 4 Recipes: A Problem-Solution Approach

    •migrating a project from ASP.NET web forms to the MVC 4 including recipes for converting DataGrids, Forms, Web Parts, Master Pages and navigation controls •Client side data binding and templating ...

    ASP.NET.MVC.5.with.Bootstrap.and.Knockout.js.1491914394

    With this practical book, you’ll learn how by combining the ASP.NET MVC server-side language, the Bootstrap front-end framework, and Knockout.js—the JavaScript implementation of the Model-View-...

    ASP.NET Core 1.1 For Beginners: How to Build a MVC Website

    The goal is to get you familiar with ASP.NET Core 1.1 by adding middleware and services one piece at a time, building a basic application. Then you will build a second MVC application using a ...

    ASP.NET MVC Flash 在线拍照

    // Adding it to the page; var pic = '/Content/' + msg.filename; //$("#photos").attr("src", pic); $("#photos").append(';" src="' + pic + '"/&gt;'); } }); //错误 webcam.set_hook('onError', ...

    Professional ASP.NET 3.5 SP1 Edition: In C# and VB(part1)

    Methods for adding AJAX capabilities to your ASP.NET applications * The many benefits of the new data access additions * Ways to use and extend the Provider Model for accessing data stores, ...

    asp.net core英文版教程

    - **Building Your First Web API with ASP.NET Core MVC and Visual Studio**:介绍如何使用 ASP.NET Core MVC 和 Visual Studio 构建第一个 Web API。 - **Deploy an ASP.NET Core web app to Azure using Visual ...

    ASP.NET Core 实战

    * Chapter 7: Model binding and validation in minimal APIs 这些章节将指导读者快速入门 ASP.NET Core,了解其基本概念和关键技术。 Part 2 Building_complete_applications * Chapter 8: An introduction to ...

    Sculpture 2.0 Model-driven development Generators(Installer)

    Sculpture comes with a host of ready-made Molds (The word “Molds” comes from Molding) like (DAAB, NHibernate, LINQ, CSLA, WCF, ASMX, Windows forms, WPF, Silverlight, ASP.NET, & ASP.NET MVC)....

    Professional.ASP.NET.2.0.AJAX

    &lt;br&gt;What you will learn from this book &lt;br&gt;How to create a better user experience by adding more dynamic UIs Steps for accessing ASP.NET profile and authentication services Ways to ...

    Sculpture 1.0 Model-driven development Generators(Installer)

    Sculpture comes with a host of ready-made Molds (The word “Molds” comes from Molding) like (DAAB, NHibernate, LINQ, CSLA, WCF, ASMX, Windows forms, WPF, Silverlight, ASP.NET, & ASP.NET MVC)....

    Sculpture 1.0 Model-driven development Generators(Source Code)

    Sculpture comes with a host of ready-made Molds (The word “Molds” comes from Molding) like (DAAB, NHibernate, LINQ, CSLA, WCF, ASMX, Windows forms, WPF, Silverlight, ASP.NET, & ASP.NET MVC)....

    Sculpture 1.0 Model-driven development Generators(Molds Source Code)

    Sculpture comes with a host of ready-made Molds (The word “Molds” comes from Molding) like (DAAB, NHibernate, LINQ, CSLA, WCF, ASMX, Windows forms, WPF, Silverlight, ASP.NET, & ASP.NET MVC)....

    Sculpture 2.1 Model-driven development Generators(Installer)

    Sculpture comes with a host of ready-made Molds (The word “Molds” comes from Molding) like (DAAB, NHibernate, LINQ, CSLA, WCF, ASMX, Windows forms, WPF, Silverlight, ASP.NET, & ASP.NET MVC)....

    Sculpture 2.1 Model-driven development Generators(Source Code)

    Sculpture comes with a host of ready-made Molds (The word “Molds” comes from Molding) like (DAAB, NHibernate, LINQ, CSLA, WCF, ASMX, Windows forms, WPF, Silverlight, ASP.NET, & ASP.NET MVC)....

    Adding a Build Banner to ASP.NET Pages

    在ASP.NET开发中,添加构建横幅是一种常见做法,它有助于开发者在页面顶部或底部显示当前应用程序的版本信息、构建日期等,以便于追踪和管理不同的应用版本。这个过程涉及了Web开发的基本概念,包括HTML、CSS、以及...

Global site tag (gtag.js) - Google Analytics