ASP.NET Core 1.0 MVC Model

Model is an object representing a data item and set of applicable operations. It can be of a simple native type like integer, string or a complex structure like class, array. Ideally, model represents the state of an application. It is said to be a data holder in MVC structure.

For data-centric applications, Model is a representation of an Entity and is generally used to transport data between Database and View through controller. For example, in Entity Framework or any ORM, Model Classes represents underlying entities.

model

It is common practice to pass custom Models to Views, called ViewModel particularly, in case of Strongly Typed Views. There are many reasons and advantages to use View Models,

  • ViewModels can be subsets of a single Model or multiple Models and they are designed to fulfill data requirements of the View without affecting the actual Model. For example, for a list page, we may use a ViewModel which has as few fields as columns, as required on list page instead of having all of the fields. On the other hand, for a complex View, we can have a composite ViewModel having fields from different Models or additional fields.

  • When we bind Model with View, then they can make Model details available in rendered HTML, but with usage of ViewModel, we can hide actual Model details. Therefore, they provide additional security.

  • It increases the performance by minimizing the data transfer to and from View.

There are many other features related with Models like the following,

  • Model Binding
  • Data Annotation and Model Validation
  • Response Data Formatting

Model Binding

Model Binding or Data Mapping is responsible to map the data from request to actual action method. For simplicity, we have to keep the following points in mid,

  • Model Binding is based on key value pair mapping and this mapping is not case sensitive, Data Elements are mapped using reflection and recursion.

  • For data mapping the following collections are checked, in order: Form, Route and then Query String. So for parameter data mapping first of all Form values are parsed, if parameter is not found in Form then Route Values are checked, Even if the value is not found then Query String is checked. If a value is not found in any of these then it is tried to set it to null.

  • ASP.NET Core provides us flexibility to change default binding behavior through predefined attributes including the following,

    • BindRequired
    • BindNever
    • FromHeader
    • FromQuery
    • FromRoute
    • FromForm
    • FromServices
    • FromBody
    • ModelBinder (It allows us to define custom data binder)

Data Annotation and Model Validation

Data Annotation is used to decorate a model. These are attributes and used to add additional details or metadata to model. This additional set of information can be used for a variety of purposes like: Labeling, Data Validation, Data Formatting, and Data Mapping.

System.ComponentModel.DataAnnotations provides a set of validation attributes. Most of the time data annotations are used for Labeling and Data Validation. Most commonly used data annotations are,

  • Required
  • StringLength
  • MinLength
  • MaxLength
  • RegularExpression
  • DataType
  • Display
  • DisplayFormat
  • Compare
  • Editable
  • CustomValidation

Basically all validation data annotations are driven from ValidationAttribute, which is driven from Attribute. Please refer to CRUD operations in ASP.NET Core 1.0 MVC Application Part 4 to see most of the data annotations in action.

We can provide custom messages as per our requirements through ErrorMessage and if we don't provide ErrorMessage then default message is used. We can also use localization through resource files to centrally control labels and messages in single or in multiple languages. For this purpose, we specify resource through ErrorMessageResourceType parameter and resource filed with ErrorMessageResourceName parameter. We can also define new data annotation to perform both the client side and server side validations. We will discuss creating new data annotations in detail in future sessions.

Required

RequiredAttribute inherits from ValidationAttribute and specifies that a data field value is required.
[Required]

StringLength

StringLengthAttribute inherits from ValidationAttribute and specifies the minimum and maximum length of characters that are allowed in a data field.

[StringLength(100, MinimumLength = 3)]

MinLength

MinLengthAttribute inherits from ValidationAttribute and specifies the minimum length of array or string data.

[MinLength(3)]

MaxLength

MaxLengthAttribute inherits from ValidationAttribute and specifies the maximum length of array or string data.

[MaxLength(100)]

RegularExpression

RegularExpressionAttribute inherits from ValidationAttribute and specifies that a data field value must match the specified regular expression

[RegularExpression("[a-zA-Z ]*$", ErrorMessage = "Name can only contain alphbetics and space.")]

DataType

DataTypeAttribute inherits from ValidationAttribute and specifies the name of an additional type to associate with a data field. We also have specific purpose data validators like CreditCard, EmailAddress, FileExtensions, Phone, Url driven from DataTypeAttribute. They are used to validate string values for specific formats acceptable for credit card numbers, email addresses, file extensions, phone numbers and Urls.

[DataType(DataType.Time)]


Display

DisplayAttribute inherits from Attribute and provides a general-purpose attribute that lets you specify localizable strings. This is basically used to display label instead of validation.

[Display(Name = "Contact Id")]

DisplayFormat

DisplayFormatAttribute inherits from Attribute and specifies how data fields are displayed and formatted.

[DisplayFormat(DataFormatString ="9,999.##", ApplyFormatInEditMode =true)]


Compare

CompareAttribute inherits from ValidationAttribute and specifies that value of a data filed is compared tothe value of other data field.

[Compare("PropertyToCompare")]


Editable

EditableAttribute inherits from Attribute and specifies that data field is editable or not.

[Editable(false)]

CustomValidation

CustomValidationAttribute inherits from ValidationAttribute and allows us to specify a custom validation method that is used to validate a property or class instance. Where we can define our custom method to perform complex tasks like validating unique email, address validation or any complex validation activity.

Response Data Formatting

ASP.NET Core supports JSON as default data format for request, and we can also use XML by using Microsoft.AspNetCore.Mvc.Formatters.Xml package. Furthermore, we can have many other formats like CSV or any other as per our requirements with custom implementations. We will discuss Response Data Formatting in detail in future sessions.

Further Reading

For further details, please refer to official documentation at MSDN.