More articles

Starting Out With ASP.NET MVC Part 3

Written by
Filed under
Published on
Modified on

Welcome to part 3 of my starting off with MVC tutorial. In this post I will be mainly going over Data Annotations. You can check out part 1 where I cover starting a brand new project from scratch. Or if you're above that level, part 2 where I cover Models and the Entity Framework.

But first a quick recap of those 2 sections.

Previously on part 1...

In part 1 I covered the very basics of starting off with ASP.NET MVC. Everything from setting up a new project in Visual Studio, to adding the necessary Controllers and Views to get a website up and running.

Previously on part 2...


In Part 2 I take things up a slight notch by introducing the concept of Models and the Entity Framework. I went over creating a brand new model, having the "Code First" model implemented in order to generate a database for us based on our code and sending the Models data to our Views.

And in this post

And now that we're all caught up, on this post I'm going to be covering a few more topics to round out this whole MVC thing, such as Data Annotations and the different types of Data Annotations that you will need to add to your models in order to get the desired results. And personally, this is one of the gray areas for me, because I think Annotations aren't intuitive enough for a web developer and they step out of the normal HTTP/HTML structure too much. Having said that, here are data annotations.

Data Annotations

You can use Data Annotations to customize your data models in a Code-First EF implementation. They are essentially added keywords, surrounded by brackets that tell your application how certain fields should be treated. Many times this is done either directly in the database, or with custom code. By setting the rules in our entity classes however, we can centralize how our entire application will deal with our model data. If say for example, we want a field in our model to only have 6 characters, we can do that by setting the appropriate data annotations and anywhere that field is used it will remember how to treat said data.

Here are a few of the more widely used ones.

  • Required – Indicates that the property is a required field
  • DisplayName – Defines the text we want used on form fields and validation messages
  • 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

You can break down Data Annotations into 3 different categories, Validation, Display, and Data Modeling. And I'll break each down below to give a better idea of how and when they're used.

In order to use Data Annotations, you'll first have to include the appropriate namespaces:


using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

And here is a simple example of a Model with various annotations set on its data.


namespace MvcMusicStore.Models
{
    [Bind(Exclude = "AlbumId")]
    public class Album
    {
        [ScaffoldColumn(false)]
        public int      AlbumId    { get; set; }
        [DisplayName("Genre")]
        public int      GenreId    { get; set; }
        [DisplayName("Artist")]
        public int      ArtistId   { get; set; }
        [Required(ErrorMessage = "An Album Title is required")]
        [StringLength(160)]
        public string   Title      { get; set; }
        [Required(ErrorMessage = "Price is required")]
        [Range(0.01, 100.00,
            ErrorMessage = "Price must be between 0.01 and 100.00")]
        public decimal Price       { get; set; }
        [DisplayName("Album Art URL")]
        [StringLength(1024)]
        public string AlbumArtUrl { get; set; }
        public virtual Genre  Genre    { get; set; }
        public virtual Artist Artist   { get; set; }
    }
}

Validation Annotations

These are used to validate your data. That includes the type of data that should be allowed by the model and whether the data is required in the application or not. Setting a property to Required for example would trigger an exception if at any point the model was void of that value. Adding the Range annotation would ensure that the numeric value being set always falls between that range. And so on.

Normally this is done on the client side. However, by adding this directly to the model itself, it will ensure these rules no matter where we are using the models.

Display Attributes

Display annotations dictate how the data is displayed and or formatted. For example:


public class Customer
{
  [DataType(DataType.EmailAddress)]
  public string EmailAddress { get; set; }

  [DataType(DataType.PhoneNumber)]
  public string Phone { get; set; }
}

These display types take care of the tedious task of validating how data is formatted and displayed. For example, setting a property to have a datatype of Email would throw an error if the content was in any other format. And the same would go for phone numbers.

Data Modeling Attributes

Data Model annotations are used to specify the intended use of data members and the relationships between data classes. EditableAttribute for example would control whether users were able to edit this field in the database. And the Key attribute would be used to specify which field is the primary key in the application.

There is definitely a benefit to using Data Annotations, as they do take care of the dirty work that comes with ensuring valid data in an application. Particularly when a model is being used more than once in an application.

We're not done with MVC just yet though. In the next post I'll cover HTML helpers in more detail and the concept of Code Migrations in ASP.NET MVC.

Walter G. is a software engineer, startup co-founder, former CTO of several tech companies and currently teaches programming for a coding bootcamp. He has been blogging for the past 5 years and is an avid BMX rider, bio-hacker and performance enthusiast.
If you read this far, then I hope you enjoyed this post and found it useful! Consider adding to my daily coffee intake to continue to provide better and more helpful articles in the future!
Maybe later

Discussion / Comments / Questions

No messages posted yet

Add a comment

Send me your weekly newsletter filled with awesome ideas
Post comment