Sunday, 18 September 2016

ASP.NET Core 1.0 MVC Model

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

For data centric applications, Model is 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 represent underlying entities.



It is common practice to pass custom models to views called as ViewModel particularly in case of Strongly Typed Views. Please refer to ASP.NET Core 1.0 MVC View for more details about Views. There are many reasons and advantages to use View Models:
  • ViewModels can be subset of a single model or multiple models and they are designed to fulfill data requirements of view without effecting actual model. For example, for a list page, we may use a ViewModel which has as few fields as few column as required on list page instead of having all of 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. Therefor they provide additional security.
  • It increase performance by minimizing data transfer to and from view. 
There are many other features related with Models like following:
  • Model Binding 
  • Data Annotation and Model Validation
  • Response Data Formatting

Model Binding

Model Binding or Data mapping is responsible to map data from request to actual action method. Please refer to ASP.NET Core 1.0 MVC Controller for more details about Controllers and Action Methods. For simplicity, we have to keep 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 following collections are checked order wise: 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 check, Even if value not found then Query String is check. If a value not found in any of these then it is tried to set it to null.
  • ASP.NET Core provide us flexibility to change default binding behavior through predefined attributes including 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 Attribute 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 data annotations in action.
We can provide custom message as per 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 of 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 format acceptable for credit card number, email address, file extensions, phone number 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 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 task 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 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:  https://docs.asp.net/en/latest/mvc/models/index.html.

No comments:

Post a Comment