Unit-3 (Model Validation and Annotation)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Unit-3

Validations & Data Annotations and State


Management Technique
What is a Model:
• Model is a class that represent structure of data(as a properties) that you
would like to receive in request and send on response.
• Action method receive a data in the form of model object and also return a
model object parameter in response.
• A model is a class that contains the business logic of the application.
• It also used for accessing data from the database.
• The model class does not handle directly input from the browser.
• It does not contain any HTML code as well.
• Models are also refers as objects that are used to implement conceptual
logic for the application.
• A controller interacts with the model, access the data, perform the logic
and pass that data to the view.
• It represents the shape of the data as public properties and business
logic as methods.
• For Example, we have to create student class inside a model which
define all property of students like,

• The model class can be used in the view to populate the data, as well
as sending data to the controller.
• If your application does not have data, then there is no need for a model. If
your application has data, then you need a model.
• in simple words, we can say that the Model is the component in the MVC
Design pattern that is used to manage the data, i.e., the state of the
application in memory.
• in that MVC Application, three things are common, i.e., Model, View, and
Controller.
• The Controllers are used to manage the overall flow of the MVC
Application.
• Models are responsible for storing the data that is used on Views.
• Views are basically the HTML Pages that get rendered into the client’s
browser. In the browser, we generally perform two operations.
• First, we display the data to the user; second, we get the data from the
user. For both these operations, models are used.
Query String and Route Parameter Binding using Model:
 Model Binding using Model Class:
• Model binding is a process in which we bind a model to controller and
view.
• It is a simple way to map posted form values to a .NET Framework
type and pass the type to an action method as a parameter.
• It acts as a converter because it can convert HTTP requests into
objects that are passed to an action method.
• Here data are stored in seprate model class and this model class
sending data to a specific action method.
• Model binding are done by three ways,
1. QueryString Parameter
2. Passing Route Parameter
3. By creating Model class.

• Workflow of Model Binding:


Model
(Responsible for storing
data)

Controller View
(send data for process (Receive data From
and result) Model)
Example:
 Model Validation:-
• Validation is an important aspect in ASP.NET MVC applications.
• It is used to check whether the user input is valid. ASP.NET MVC
provides a set of validation that is easy-to-use and at the same time.
• it is also a powerful way to check for errors and, if necessary, display
messages to the user.
• These validations ensure that the user fills in the correct data into the
application so that we can process that data and save it for future
use.
• Normally, users always fill out the form with the necessary
information and submit it.
• we notice that the site gives us some error message or warning
message.
• when we do not put properly formatted data in the form's controls.
Normally, we receive the message as below –
1. The field value is required. We can’t leave the field blank.
2. Please enter your data in the correct format in case of phone number, date
of birth, etc.
3. Please provide a valid email address.
4. Your password does not match the format like uppercase, one symbol, and
one number.
• This type of message is known as form validation.
 Validation Types :-

Validations

Server-Side Validations Client-Side Validations


1.Server-side validations:-
• It required for data are validate before processing on data.
• It Check user input is validate if data are not in proper manner so
server send validate message.
• It used when we have to require model and database validation.
2.Client-side Validations:-
• validation is done by the scripting languages on the client side.
• By using this type of validation, we can implement much more
responsive and visually rich validation of the user's input data on the
client side.
• The best thing about this type of validation is that the form submit
method is not executed in this case if validation fails.
 Built-In ServerSide Model Validations:-
• inbuild available validation attributes in the Asp.Net Core –
1. Required- This validation attribute makes any property required or
mandatory.
2. StringLength-This validation attribute validates any string property
along with its length
3. Compare-This validation attribute compares the two property
values in a model match
4. EmailAddress-This validation attribute validates the email address
format
5. Phone -This validation attribute validates the phone no format
6. CreditCard-This attribute validates a credit card format
7. Range-This validation attributes any property to check whether it
exists within the given range or not.
8. Url-This validation attribute validates whether the property contains
a URL format or not
9. RegularExpression-This validation attribute normally matches the
data which specified the regular expression format.
Example:-
Passing data from controller to view:
• There are three objects to passing data from controller to view,
1]ViewData:-
• It passes data from controller to view.
• Syntax:
• ViewData[“<key>”]=<value>;
• Where,key is a string value of object
Value may be list,object,array, and any type of data.
• The life of the ViewData Object exists during the current request.
• Value of the ViewData becomes NULL the request is redirected.
• ViewData required type casting when complex datatype( like
int,char,string,float) will be used.
• It does not define compile time error but it only generate run-time
error.
2]ViewBag:-
• It passes data from controller to view.
• Syntax:
ViewBag.<PropertyName>=<value>;
Where,
propertyName is a string value & Value may be list,object,array, and any type of
data.
• ViewBag exists only for the current request and becomes null if the request
is redirected.
• ViewBag is a dynamic property based on dynamic features.
• It does not required typecasting when you use complex data type.
• It only generate runtime error.
• ViewData and ViewBag can access each other data interchangeably.
3]TempData:
• It passes data from controller to view.
• Syntax:
• ViewData[“<key>”]=<value>;
• Where,key is a string value of object
Value may be list,object,array, and any type of data.
• It is used only for current or subsequent request as it is a very short
lived instances.
• Using TempData we only access data in only one page.
• If same data access to another page then data will be lost.
• So this data are visible in multiple view we can use keep() after
tempdata.
• It access temporarily data
• Tempdata will be cleared after completion of subsequent request.
• Call TempData.Keep() which keep value of tempdata in a third
request.

• Note: write one example for each object


TagHelpers
• Tag Helper are basically special attributes provided by Asp.net Core.
• Tag Helpers enable server-side components to participating in
creating html elements in views.
• TagHelpers are a new features as compare to html tag.
• There are many built-in tag helpers for common tasks, such as
creating forms,hyperlinks,loading assets etc.
• Tag helpers are authored in c# and they target HTML elements based
on the element name.
• For example:
• The built-in LAbelTagHelper can target the HTML <label> element when the
LAbelTagHelper attributes are applied.
• Before using tag helpers, you must have include namespace for tag helpers
in ViewImports file.
• Add this two line in your viewImports file.
• @addTagHelper.*;
• Microsoft.AspNetCore.Mvc.TagHelpers
• @addTagHelper is a directive.
• Benefits of TagHelper:
1. An HTML-friendly development experience.
2. A rich IntelliSense environment for creating HTML and Razor markup.
3. A way to make you more productive and able to produce more robust,
reliable, and maintainable code using information only available on the
server
• Example:
<form asp-action=“contactus.cshtml” asp-controller=“Home”>
……………….
</form>
List of TagHelper:
Html Tag TagHelper

1. Form TagHelper Asp-for,


asp-controller,
asp-action,asp-route
2. Label TagHelper Asp-for
3. Input TagHelper Asp-for
4. Vlidation -TagHelper Asp-validation-for
 DataBase Connectivity Using EntityFrameWork Core:
ORM(Object Relational Mapping)
• To address the data access requirements of ASP.Net Core MVC
application, you can use an ORM framework.
• ORM tool define process of accessing data from applications.
• ORM is a tool for storing data from model classes to sql server
database.
Workflow of ORM tool :
EntityFramework Core
• Entity Framework Core is the new version of EF Core 6.
• It is open-source,lightweight,extensible and a cross platform version
of entity framework.
• Entity framework core is a data access technology.
• EF Core support two approaches for database connectivity,
• 1]code-first connectivity
• 2]Database-first connectivity
1.Code first connectivity:
• In the code-first approach the EFCore creates database objects based
on model classes that you create to represent application data.
• In this approach application develop by model class and properties
and delegate process of creating the database objects to EFCore.
• The code-first approach allows you to define your own model by
creating custom classes.
• Then you can create database based on the models.
 Steps for CodeFirst Connectivity:
• Step-1:
• Step-2:

• Step-3:

"ConnectionStrings": {
"dbcs3":
"Server=127.0.0.1;port=3307;Database=Stud;user=root;password=;“}
• Step-4:

var provider= builder.Services.BuildServiceProvider();


var config = provider.GetService<IConfiguration>();

builder.Services.AddDbContext<StudentDBContext>(item =>
item.UseMySql(builder.Configuration.GetConnectionString("dbcs3"),
ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("dbcs3"))
));
• Step-5:
DbContext File:
2]: DatabaseFirst Connectivity:
Steps for DatabaseFirst Connectivity:
• Step-1:

• Step-2:
• Note: When example are required so please define example in
specific points

You might also like