Computer Magic Logo
Model

Sunday, November 22, 2015

Published by Aristotelis Pitaridis

The first thing that we have to create is the contact form model. We create a new class called ContactFormViewModel and we store it in the App_Code folder of our project.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ComputerMagic.Models
{
    public class ContactFormViewModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        public string EMail { get; set; }

        [Required]
        public string Message { get; set; }
    }
}

As we can see we have three properties which are the name, the e-mail and the message that the user will type in the form. We used data annotations for the model properties which describes what the user is supposed to type in the form for each of the form fields. The Required data annotation forces the user to type something otherwise the form is not going to save the information. The EmailAddress data annotation checks if the user has typed a valid e-mail. These data annotations are standard ASP.NET MVC data annotations and we can use more of them in order to cover more validations. There are more ASP.NET MVC data annotations, but that’s beyond the scope of this tutorial.

For each of these data annotations the system will generate an error message in case that the user has not typed an expected value. If we want to define our own error message we will have to define them inside the data annotation so let’s see how to do it.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ComputerMagic.Models
{
    public class ContactFormViewModel
    {
        [Required(ErrorMessage = "The field Name is a required field.")]
        public string Name { get; set; }

        [Required(ErrorMessage = "The field E-Mail is a required field.")]
        [EmailAddress(ErrorMessage = "You have to type a valid E-Mail")]
        public string EMail { get; set; }

        [Required(ErrorMessage = "The field Message is a required field.")]
        public string Message { get; set; }
    }
}

As we can see the error messages are strings which can be changed and we can define whatever we want.