Currently, the Create and Edit forms you have in place do not perform any kind of validation. If the user leaves a required field blank or type letters in the price field, the first error you will get will be from the database.
You can add validation to the application by adding Data Annotations to your model class. Data Annotations allow describing the rules you want applied to your model properties, and ASP.NET MVC will take care of enforcing and displaying appropriate message to users.
Additionally, you will add client-side (AJAX) validation that will check all fields in the browser before being submitted to the controller actions.
Task 1 – Adding Data Annotations
In this task you will add Data Annotations to the Album Model that will make the Create and Edit page display validation messages when appropriate.
- Start Microsoft Visual Web Developer 2010 Express from Start | All Programs | Microsoft Visual Studio 2010 Express | Microsoft Visual Web Developer 2010 Express.
- In the File menu, choose Open Project. In the Open Project dialog, browse to Source\Ex06-AddingValidation\Begin, select MvcMusicStore.sln and click Open.
Note:For a simple Model class, adding a Data Annotation is just handled by adding a using statement for System.ComponentModel.DataAnnotation, then placing a [Required] attribute on the appropriate properties.
The following example would make the Name property a required field in the View.
using System.ComponentModel.DataAnnotations;
namespace SuperheroSample.Models
{
public class Superhero
{
[Required]
public string Name { get; set; }
public bool WearsCape { get; set; }
}
}
This is a little more complex in cases like this application where the Entity Data Model is generated. If you added Data Annotations directly to the model classes, they would be overwritten if you update the model from the database.
Instead, you can make use of metadata partial classes which will exist to hold the annotations and are associated with the model classes using the [MetadataType] attribute. - Add a new metadata partial class. To do this, right-click the Models folder within the Solution Explorer, select Add and then New Item.
- In the Add New Item dialog box, select the Class template, located under Visual C#,Web template list. Change the name to Album.cs and click Add.

Figure 32
Adding Album.cs - Replace Album.cs content with the highlighted code, so that it looks like the following:
(Code Snippet – ASP.NET MVC 2.0 Helpers, Forms and Validation – Ex6 Album metadata partial class – CSharp)
C#
Copy Code
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MvcMusicStore.Models { [MetadataType(typeof(AlbumMetaData))] public partial class Album { // Validation rules for the Album class [Bind(Exclude = "AlbumId")] public class AlbumMetaData { [ScaffoldColumn(false)] public object AlbumId { get; set; } [DisplayName("Genre")] public object GenreId { get; set; } [DisplayName("Artist")] public object ArtistId { get; set; } [Required(ErrorMessage = "An Album Title is required")] [DisplayFormat(ConvertEmptyStringToNull=false)] [StringLength(160)] public object Title { get; set; } [DisplayName("Album Art URL")] [StringLength(1024)] public object AlbumArtUrl { get; set; } [Required(ErrorMessage = "Price is required")] [Range(0.01, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")] public object Price { get; set; } } } }
Note:This Album partial class has a MetadataType attribute which points to the AlbumMetaData class for the Data Annotations. These are some of the Data Annotation attributes you are using to annotate the Album model:
•Required – Indicates that the property is a required field
•DisplayName – Defines the text to be used on form fields and validation messages
•DisplayFormat – Specifies how data fields are displayed and formatted.
•StringLength – Defines a maximum length for a string field
•Range – Gives a maximum and minimum value for a numeric field
•Bind – Lists fields to exclude or include when binding parameter or form values to model properties
•ScaffoldColumn – Allows hiding fields from editor forms
Note: |
|---|
| The line [DisplayFormat(ConvertEmptyStringToNull=false)] indicates that empty strings from the model won’t be converted to null when the data field is updated in the data source. This setting will avoid an exception when the Entity Framework assigns null values to the model before Data Annotation validates the fields. |
Task 2 – Running the Application
In this task you will test that the Create and Edit pages validate fields, using the display names chosen in the last task.
- Press F5 to run the Application.
- The project starts in the Home page. Change the URL to /StoreManager/Create. Verify that the display names match the ones in the partial class (like Album Art URL instead of AlbumArtUrl)
- Click Save, without filling the form. Verify that you get the corresponding validation messages.

Figure 33
Validated fields in Create page - You can verify that the same occurs with the Edit page. Change the URL to /StoreManager/Edit/388 and verify that the display names match the ones in the partial class (like Album Art URL instead of AlbumArtUrl). Empty the Title and Price fields and click Save. Verify that you get the corresponding validation messages.

Figure 34
Validated fields in Edit page
Task 3 – Adding Client-Side (AJAX) validation
In this task you will add client-side (AJAX) validation to the forms to check all fields in the browser before being submitted to the controller actions.
- Close the browser if needed, to return to the Visual Studio window. Open /Views/Shared/EditorTemplates/Album.ascx
- Include the needed references to the libraries that will take care of the client-side validation:
HTML
Copy Code
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMusicStore.Models.Album>" %> <script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> <script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
- Use the Html.EnableClientValidation helper method to turn on client-side validation. For both the Create and Edit view templates, add that call directly above the Html.BeginForm call. In order to do that, open /Views/StoreManager/Create.aspx and /Views/StoreManager/Edit.aspx and add the following:
(Code Snippet – ASP.NET MVC 2.0 Helpers, Forms and Validation – Ex6 Client-Side validation – CSharp)
C#
Copy Code
<% Html.EnableClientValidation(); %> <% using (Html.BeginForm()) {%> <%: Html.ValidationSummary(true) %> <fieldset> - Edit the Web.config in the project root to disable UnobtrusiveJavaScript. To do this, replace the appSettings entry with the following one:
XML
Copy Code
<configuration> <appSettings> <add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="false"/> </appSettings>
Task 4 – Running the Application
In this task you will test that the Create and Edit pages validate fields in the browser before being submitted to the controller actions.
- Press F5 to run the Application.
- The project starts in the Home page. Change the URL to /StoreManager/Create. Enter a letter in the Price field and click anywhere else in the form, taking focus out of the text box. Verify that without submitting the form, the corresponding validation message appears.

Figure 35
Validated fields at client-side - Delete the letter entered in the Price field and verify that the appropriate validation message appears without submitting the form.

Figure 36
Validated fields at client-side