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.
- 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:
[StringLength(100, MinimumLength = 3)]
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.
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]
[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)]
[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)]
[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.
Wonderful thanks for sharing an amazing idea. keep it...
ReplyDeleteGet Business Analyst Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.
This wonderful article awesome content and presentation look like your blogs.
ReplyDeletepython online training
python flask training
python flask online training
Python Training in Chennai
Python Training in Training
Python Training in Bangalore
Python Hyderabad
Python Training in Coimbatore
I appreciate that you produced this wonderful article to help us get more knowledge about this topic.
ReplyDeletejava training in chennai
java training in omr
aws training in chennai
aws training in omr
python training in chennai
python training in omr
selenium training in chennai
selenium training in omr
Thanks for sharing this unique and informative content which provided me the required information.
ReplyDeletehadoop training in chennai
hadoop training in tambaram
salesforce training in chennai
salesforce training in tambaram
c and c plus plus course in chennai
c and c plus plus course in tambaram
machine learning training in chennai
machine learning training in tambaram
I just loved your article on the beginners guide to starting a blog.If somebody take this blog article seriously in their life, he/she can earn his living by doing blogging.thank you for this article.
ReplyDeleteangular js training in chennai
angular js training in velachery
full stack training in chennai
full stack training in velachery
php training in chennai
php training in velachery
photoshop training in chennai
photoshop training in velachery
Wow, that is appealing studying. i am glad i found this and were given to artifice in it. great task upon this content. I preferred it loads. thanks for the colossal and precise data. Driver Genius Crack
ReplyDelete