Net Core MVC
Net Core MVC
What is controller?
Controller Concepts :
MVC Controller – Empty – it cretas an empty controller.
MVC Controller with read/write – this template will create the
controller with 5 action methods to create, to read, to update, to
delete and list entities.
MVC Controller with views using entity framework – this template will
create and mvc controller with actions and razor views to create, to
read, to update, to delete and list entities using entity framework core.
Razor Views: These are most common views in mvc razor views using a
razor syntax means combination of html and c#.
Task:
Take array of number from 1-20 then print, write a print method and
call in main method, then apply the following methods.
Prime number();
Even number();
Odd number();
Reverse number();
====================================================
24/08/2024
Create a new project of [Link] core[mvc] and name it as
“HRMProject”.
Right click on model’s folder and add class and name it has
“Products.”, define properties
[Key]
public Guid ProductId {get; set;}
public string ProductName {get; set;} = [Link];
public decimal Price {get; set;}
Short cut for creating property is PROP
}
Create a Dbset .
public DbSet<Product> Products { get; set; }
in this, off brackets(<>) we are giving model name.
Right click on controller and create controller and select template as
MVC controller read/write actions name as ProductsController, while
adding its showing error.
o To solve the above error we need to check the migration.
o Open tools, manage nuget, package manager console.
o Type add-migration productmigration
Unable to create a 'DbContext' of type ''. The exception 'Unable to
resolve service for type
'[Link]`1[HRMProject.H
[Link]]' while attempting to activate
'[Link]'.' was thrown while
attempting to create an instance. For the different patterns supported
at design time, see [Link]
Again do migration.
Update-database, it will update the schemas to the database.
Right Create on a controller folder and add controller with entity .
In program,cs change the controller name
pattern: "{controller=Products}/{action=Index}/{id?}");
25/08/2024
DbFirstApproach:
Create a new project with [Link] Web App(Model-View-Controller)
and give project name as “DbFirstApproach”.
Install 4 packages,
[Link]
[Link]
[Link]
[Link]
Open package manager console, write a command like
PM> Scaffold-DbContext "Data Source = DESKTOP-78H5NU7;
Database = HRM; TrustServerCertificate = True; Integrated
Security = True" [Link] -
OutputDir Models
It generates a [Link] page.
Right click on controller folder and add controller with MVC Controller
with views, entityframework template. Then select Model class and
DbContext then click on add.
In [Link] file, write the below code,
[Link]< HrmContext>();
//<HrmContext> is a generated Model file, give the classname.
And change the controller’s name.
Run the application.
Note : when we give the GUID as a datatype, for adding next record we
need to select the new Id in SQL server. select NEWID()
Task:
[Link] is DBFirst Approach in EntityFramework core?
[Link] is CodeFirstApproach in EntityFramework Core?
[Link] between DBFirstApproach and CodeFirstApproach?
1. This approach is useful when working with existing databases or
complex database structures. It can also be suitable for large applications
that rely heavily on data. The database first approach can offer rapid
development and integration with minimal code writing. It can also make it
easier to map and create keys and relationships, since developers don't
need to write them in code. However, it might result in less control over the
generated code and could potentially lead to a less domain-driven
approach to application design.
27/08/2024
GitHub Process: push to origin branch(vs)
Search Git in google.
Select downloads of windows 64-bit.
Installed and click next.
Search download GitHub Desktop.
Click on download for windows (64bit).
After downloading, click on create free account?
Enter your email, password, username.
To fetch the updates from the main branch,
o First select current branch.
o Then choose branch to merge, select main branch.
o Click on “Create a merge commit”.
PostMan:
APIs will be tested here when we use web API.
28/08/2024
LINQ: Linq means language integrated query. It is a powerful set of
technologies based on the integration of query capabilities directly into the
C# language. Linq queries are the first-class language constructrd in c# just
like classes, methods and events. Ling provides a consistent query
experience to query objects, relational database and XML files. Linq is a
uniform query syntax in c# to retrieve data from difference source and
formats. Linq query return results an object. It enables you to use object-
oriented approach on the result set.
It’s a case sensitive, same as c# language.
Program: example for LinqQuery syntax
Output:
Ball
James
Mohan
Syntax:
The LINQ query syntax starts with from keyword and ends with
select keyword.
29/08/2024
Difference between IQueryable and IEnumerable:
[Link]<T>: It works with in-memory collection.
Example: Arrays
It executes queries in-memory after all data is loaded.
It is potentially less efficient with large data sets since it pulls all data
into memory before applying the query.
The queries are applied to data already in-memory
IQueryable:
It works with data sources that support querying such as databases.
It constructs and executes query at data source and the query is
translated and optimized before execution.
It is more efficient with large data sets and remote data sources as
queries are executed at the server or database level.
It builds and expression tree that is translated into a query suitable for
the data source.
Fetching the data is called querying, larger data is display here.
When we have list, that time will use IEnumerable.
While fetching data we can use IEnumerable when it has smaller data
and it filters the data also.
Example for IEnumerable:
List<Customer> customers = new List<Customer>
{
New customer {Id=1, Name=”Alice”, Age=30}
New customer{Id=2, Name=”Bob”,Age=25}
New customer{Id=3, Nmae=”Charlie”, Age=35}
};
//IEnumerable query: applies the filter in memory
IEnumerable<Customer> filteredCustomers =
[Link](c=>[Link]>=30); //Query is executed in-memory
Foreach(var customer in filteredCustomers)
{
[Link]($”{[Link]},{[Link]},{[Link]}”);
}
Class Customer
{
Public int Id {get; set;}
Public string Name {get; set;}
Public int Age {get; set;}
}
Task:
[Link] is difference between IEnumerable and IQueryable?
[Link] is IQueryable?
[Link] is IEnumerable?
[Link] is the impact of IQueryable on performance compare to
IEnumerable?
[Link] u explain when to use IQueryable and IEnumerable?
30/08/2024
Structure of LINQ Query Syntax:
Var result = from s in strList
where [Link](“tutorials”)
Select s;
result = Result variable
s = range variable
strList = sequence(IEnumerable or IQueryable)
from, select = standard query operators
Contains = conditional expression
Example:
Output: Java
Example:
Lambda Expression:
The Lambda expression is a shorter way of representing anonymous
method using a special syntax.
It is defined by =>
Lambda expressions with multiple parameters.
Lambda expressions with specified parameters type.
Lambda expressions with specified multiple parameters.
Lambda expressions without parameters.
Lambda expressions with multiple statements in lambda expression
body.
Declare local variable in lambda expression body.
Assign lambda expression to delegate.
Assign delegate with lambda expression assign to action delegate.
Lambda expression in linq query.
Lambda Expression Syntax:
S => [Link] > 12 && [Link] < 20;
Here, s = parameter
=> - Lambda operator
[Link] > 12 && [Link] > 20 - body expression
[Link] Expression with multiple parameters
Task:
[Link] is query syntax?
[Link] is method syntax?
[Link] between query syntax and method syntax?
[Link] is lambda expression, how will you define?
[Link] many ways we are defining lambda expression can you define?
31/08/2024
Standard Query Operators:
Standard query operators in LINQ are actually extension methods for
the I Enumerable<T> and IQueryable<T> types.
They are defied in the [Link] and
[Link] classes.
They are over 50 standard query operators available in Linq.
That provide different functionality like sorting, filtering,
concatenation, grouping, aggregation etc.
[Link]:
standard operator
Where
Of type
[Link]:
Standard operators of Sorting
OrderBy
OrderByDescending
ThenBy
ThenByDescending
Reverse
[Link]
Standard operators of Grouping
GroupBy
ToLookUp
[Link]
Standard operators of Join
GroupJoin
Join
[Link]
Standard operators of projection
Select
SelectMany
[Link]
Standard operators of aggregation
Aggregate
Average
Count
LongCount
Max
Min
Sum
[Link]
Standard operators of Qualifiers
All
Any
Contains
[Link]
Standard operators of Elements
ElementAt
ElementAtDefault
First
First or Default
Last
Last or Default
Single
Single or default
[Link]
Standard operators of Set
Distinct
Except
Intersect
Union
[Link]
Standard operators of Partition
Skip
Skip while
Take
Take while
[Link]
Standard operators of Concatenation
Concat
[Link]
Standard operators of Equality
SequenceEqual
[Link]
Standard operators of Generation
DefaultEmpty
Empty
Range
Repeat
[Link]
Standard operators of Conversion
AsEnumerable
AsQueryable
Cast
ToArray
ToDictionary
ToList
Filtering Operators:
Filtering operators in linq filter the sequence based on given criteria.
We have 2 types of filtering operators.
o Where
o OfType
[Link]:
The Where operator filters the collection based on a given criteria
expression and return new collection.
The criteria can be specified as a lambda expression or funk delegate
type.
Example:
[Link]:
The OfType operator filters the collection based on the ability to cast
an element in a collection to a specific type.
Use of OfType operator to filter the collection based on each element
type.
Example:
In [Link] file,
KeyPoints:
The where operator filters the collection based on a predicted
function.
The OfType operator filters the collection based on a given type.
Where and OfType extension methods can be called multiple times in
a single linq query.
Sorting Operator:
A Sorting operator arranges the elements of the collection in ascending or
descending order.
[Link]:
It sort the values of a collection in ascending or descending order.
It sorts the collection in ascending order by default, why because
ascending keyword is optional here.
[Link]:
It sorts the collection in descending order
OrderByDescending is valid only with a method syntax.
It is not valid in query syntax because the query syntax uses
descending attributes.
KeyPoints:
Linq query syntax supports multiple sorting fields separated by comma (,)
where ever you have to use “OrderBy” and “OrderByDescending” method.
05/09/2024
[Link]:
The group join operator perform the same task as join operator
except that group join returns a result in group based on specified
group key.
The group join operator joins two sequences based on key and
groups.
The result by matching key and then return the collection of group
results and key.
Group join requires same parameters as joins.
It works as a left join.
Example:
Key differences in result:
Join(inner join) : only customers with matching orders are included.
GroupJoin(Left join): all customers are included for those without orders,
the orders group is empty.
Explanation:
Join: Filters customers who have orders. It’s a one to one or many to one
match between the two collecions.
GroupJoin: Groups the orders under each customer, providing a more
hierarchical structure where even customers without orders are includes.
[Link]:
Select operator always returns an IEnumerable collection which
contains elements based on a transformation function.
Its similar to select clause in sql.
It produce a flat result set.
The linq query syntax must end with a select or GroupBy clause.
06/09/2024
[Link]:
In linq, selected many operator is used to project each element of a
collection into an IEnumberable<t> and flatten the result collections
into a single collection.
It can be combining the results of multiple sequence into one single
sequence.
Example:
Grouping Operators:
This operator do the same thing as the “GroupBy” clause of sql query.
The grouping operators create a group of elements based on the
given key.
There is a 2 types of grouping operators.
[Link]
[Link]
[Link]
The GroupBy operator returns a group of elements from the given
collection based on some given key value.
Each group is represented by IGrouping<key>,<value> object.
GroupBy method as 8 overload methods.
[Link]: ToLookUp is the same as GroupBy, the only difference is
GroupBy execution is deferred, whereas ToLookUp execution is immediate.
Also, ToLookUp is only applicable I method syntax. ToLookUp is not
supported in the query syntax
Example:
[Link] Operator: The distinct extension method returns a new
collection of unique elements from the given collection.
Example:
One-to-one Relation:
Create a project as “OneToOneRelation”.
Install 4 packages.
In [Link] file, give the connection to the server.
o "ConnectionStrings": {
o "con": "Data Source = DESKTOP-78H5NU7; Database =
OneToOne ; TrustServerCertificate = True; Integrated Security
= True;"
o },
Right click on models folder and create a class and name it as
“[Link]”
o
Right click on models folder and add class name as
“[Link]”
o
o Add-migration onetoone
Update the migration
o Update-database
Check in sql server, whether the data is updated or not.
One-To-One Relation:
One-to-one relationship in mvc involves defining and managing the
connection between two models such that each instance of one
model relates to exactly one instance of another.
The mvc pattern ensure that the data and its relationships are
managed by model that presented by view and manipulated by
controller.
The concepts of helping in structing and managing data of objects
with in application in mvc.
[Link] Management: This refers to the life cycle and visibility of data or
objects.
It determines how long data can share across different
components or request in an application.
[Link] Management: This concept describes objects or data that
exits only temporarily often for the duration of a single request or session.
This is also known as request scope or session scope.
[Link] Management: A design pattern that ensures a class has only
one instance an provide global point of access to that one instance.
Summary:
[Link] management: It manages the visibility life style of objects.
[Link]: It refers temporary objects that are only for short period.
[Link]: A design pattern ensures a single instance of a class and a
global access point.
Those concepts help in structing and managing data and object with in
application.
14/09/2024
Return Types:
[Link]: The most versatile return type. It represents a result of an
action method and allows for only different kinds of responses.
[Link]<T>: A generic version of action result that allows returning
a specific type “T”, along side the action result. Useful for API’s and actions
that return both models and different result types.
[Link]<T>: Used for returning collect of items in API controller.
[Link] core automation serializes this to Json.
4.T(Model): When returning a single object model especially in Web API
controller, the model is automatically serialized to Json.
[Link]:
Async: Marks a method as asynchronous. It returns task<t> or
void.
Await: Pauses the execution of the async method until the
awaited task completes allowing other operations to continue.
Task<IActionResult>: Uses for asynchronous operations allows
the action method to perform asynchronous work and return
Iaction result.
TaskActionResult<T>: Asyncronous version of actionresult<t>.
Useful for when per a asynchronous operations that return a
specific type.
ContentResult: Return plain text content. Useful for when you
want to return simple string or html.
FileResult: Returns a file to the client its commonly ued for file
downloads.
RedirectToActionResult: It redirect to another action method. It
can be used to navigate to different actions with in the same
controller or different controller.
Http Verbs: Http herbs are fundamentals to restful APIs and web
applications.
Each verb serves a different purpose when interacting with resources
on a server.
List of Http verbs:
HttpGet, HttpPost, HttpPost, HttpPatch, HttpDelete, HttpHead, HttpOptions,
HttpTrans, HttpConnect.
16/09/2024
Data Passing Techniques:
[Link]: It is a dictionary object in [Link] core mvc that allows us to
pass data from a controller action method to view.
It provides a flexible way to pass data allowing us to use key, value
pairs.
viewdata is useful when we need to pass dynamic data or data that
doesn’t fit well into a strongly type model.
Example:
In [Link] file,
In [Link] file,
In [Link] file.
Advantages of ViewData:
viewdata does not provide type safety; it stores data as an object
only.
We need to cast the data to the appropriate type when retrieving it.
Viewdata returns null, if a key does not exist so need to check for null
or use the “?” to avoid exceptions.
Viewdata is best to small amount of data.
Viewdata is a dynamic object, so we can pass any datatype.
ViewBag:
View bag is a dynamic object that provides a way to pass data from
the controller action method to view.
It allows us to create properties dynamically and add properties to the
viewbag object in the controller actions which are accessible in views.
[Link](): The load method, loads the tempdata values from the current
http context.
The framework typically invoke this method internally and it is not
commonly used directly in application core.
[Link](): The save method is used to save the current state of tempdata
into the HttpContext.
Its typically called automatically by the [Link] core framework at the
end of request ensuring that any changes made to tempdata during
the request or persistent/hold/save for the next request.
[Link](): The keep method marks all items in tempdata to be retain for the
next request.
This method is useful to ensure that tempdata is not cleared after
reading.
[Link](): This method reads an item from tempdata without removing it.
This is useful when you need to access the same tempdata items across
multiple request or in multiple places with in the same request.
The peek allows the data to be read and still remain in tempdata for
further request.
Example:
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
18/09/2024
Strongly Typed View In [Link] Core MVC:
A strongly typed view in [Link] core mvc is also associated with
specific class known as view model.
This class defines the data and behavior, the view needs to display or
interact with.
It is a view that except a specific data model to pass and inform to
controller action method.
Routing:
What is routing in [Link] core mvc?
Routing in [Link] core mvc is a mechanism that inspects the incoming
“HttpRequest” and then maps that request to the appropriate controller
actions.
19/09/2024
[Link](): It reads the value without marking it for deletion in the
current request, but if you access it using tempdata <key> afterward it will
be removed unless you call keep method explicitly.
Use case: When you want to read the value without consuming it
immediately, but you don’t want to persist or maintain the value for future
request.
Custom Html Helpers: you can create custom html helpers by defining
reusable methods to generate specific html markup. These helpers are
typically used when you need custom functionality that the built-in helpers
do not provide.
Form Helpers: Help generate form elements and manage the form
submissions. Example includes,
[Link]()
[Link]()
20/09/2024
Example for Html helpers:
In [Link] file,
In [Link] file,
In [Link] file,
23/09/2024
Tag Helpers in MVC:
Tag helpers in mvc allows server-side code to participate in creating
and rendering html elements in razor views.
They provide a way to add server-side functionality to html elements
in a more readable way than traditional html helpers.
Tag helpers enhance html elements with attributes that generates
dynamic html and allows developers to create more maintainable
templates.
Key Characteristics:
Tag helpers use html like syntax which allows to create, to edit and
razor view easily.
Tag helpers support model-binding.
Tag helpers support encapsulate the rendering logic and can be
reused across different views and reducing code duplication.
We can create custom tag helpers also.
24/09/2024
Dependency Injection: It is a design pattern it is used to implement
inversion of control. It allowing a program to follow the dependency
inversion principle.
It enables to create a dependent objects outside of the class and
provide those objects to a class in various ways.
Key Points:
DI promotes loosely coupling between classes and making them
easier to manage and test.
Instead of a class creating its own dependencies and it receives them
from an external source.
Types of Dependency Injection:
[Link] injection
[Link] injection
[Link] injection
Limitations:
It introduces additional complexity in configuration and understanding
for new developers.
Runtime resolutions of dependencies can slightly impact perform.
Debugging is difficulty.
Improper handling of service lifetimes can lead to memory leakage or
unwanted behavior.
Example:
Create service file, In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
On Product folder create model, and names it as [Link]. In
[Link] file,
In home controller folder, in [Link] file,
In [Link] file,
25/09/2024
Data Binding Attributes:
[Link]: The data bind from the body of the HttpRequest.
This is commonly used for Json payloads in post request.
The model binder reads the body and deserialize into the specific
model type.
Example:
Public class MyModel
{
Public string Name{get;set;}
Public int Age{get;set;}
}
[HttpPost]
Public IActionResult Create([FromBody] MyModel model)
{
If([Link])
{
//process the model
return ok();
}
return Badrequest(Modelstate);
}
[Link]: Binds data from form fields in a post request.
This is useful for traditional webforms where data sent as key value
pairs.
Example:
Public class MyFormModel
{
Public string FirstName{get;set;}
Public string LastName{get;set;}
}
[HttpPost]
Public IActionResult SubmitForm([FromForm] MyFormModel formModel)
{
if([Link])
{
//process the form data
return RedirectToAction(“success”);
}
return view(fromModel);
}
[Link]: Binds data from the query string of the url.
This is commonly used for get request such as filtering.
Example:
[HttpGet]
Public IActionResult Search([FromQuery] string query, [FromQuery] int
page=1)
{
//use the query and page parameter to perform a search
return view();
}
[Link]: binds data from route parameters specified in the url.
This is useful for APIs where identifiers are part of the url.
Example:
[HttpGet(“Products/{id}”)]
Public IActionResult GetProduct([FromRoute] int id)
{
//retrieve the product by id
return view();
}
[Link]: binds data from the HTTP Request headers.
This can be used to read custom headers or standard errors.
Example:
[HttpGet]
Public IActionResult GetData([FromHeader] string authorization)
{
//use the authorization header for passing
return ok();
}
[Link]: Binds parameters from the dependency injection
container.
This allows you to direct inject service into your action method.
Example:
Public class ProductController : Controller
{
Public ProductController()
{
}
Public IActionResult Index([FromServices] IProductService
productService)
{
Var product = [Link]();
Return view(product);
}
}
Attributes:
1.[InsertAuthorize]: The purpose of authorize attribute to restrict access to
users.
2.[AllowAnonymous]: The purpose is to allow access to anonymous
users.
3.[HttpGet], [HttpPost], [HttpPut], [HttpDelete], [HttpHeader],
[HttpOptions]: It specifies the Http methods.
4.[Route]: It specifies custom routing.
5.[Produces]: It specifies response type.
Filters:
[Link] filter: checks if a user is authorized.
[Link] Filter: Executes code before and after an action method.
[Link] Filter: Executes code before and after the result is generated.
[Link] Filter: Handles exceptions that occur during action execution.
[Link] Filter: Executes code before and after resource execution.
28/09/2024
Example on Authorization Filter:
Right click on project name and add class and name it as
[Link], in that file write below code.
In [Link] file,
Create views for the Authorized, RoleBased, Unauthorized
methods.
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file,
30/09/2024
Example for CustomResult filter:
Create a controller, In [Link] file,
In [Link] file,
In [Link] file,
In [Link] file
01/10/2024
Middleware: In [Link] core mvc, middleware is a software that sit
between the incoming Http request and the application logic processing the
request before they reach the mvc pipeline or response before they sent
back to the client.
Middleware is typically used for task like authentication, logging and
exception handling etc.
Built-in Middleware’s:
[Link] Middleware: It handles authentication and authorization.
[Link] Middleware: It catches exceptions and handles
error pagers or logger.
[Link] Middleware: Routes requested to specific end points.
[Link] Middleware: It serves static files like images, json files and
css files.
[Link] Middleware: It handles cross origin resource sharing.
05/10/2024
Views in MVC: views are components in the mvc architecture that are
responsible for rendering the user interface they take data from model and
present in a format i.e, suitable for interaction.
[Link] Folder
Controller View
[Link] Folder
_layout.cshtml
_viewimports.cshtml
_viewstart.cshtml
In [Link] file,
In [Link] file,
WEB API
07/10/2024
Introduction:
A web Api(Application Program Interface) in the context of [Link] is
a core that allows you to build Http services. Those services can be
consumed by wide range of clients such as browsers, mobile devices
and desktop.
Web Api are mainly used to develop restful services which expose
data via standard http methods like Get, Post, Put, Patch, Delete etc.
In [Link] file,
o
In [Link] file,
o
In Package Manager console, do migration.
o Add-migration studentmigartion
o Update-database
Then we need to check in sql server, data is created or not.
16/10/2024
In DB First Approach, if we add the columns to the existing table, to
implement it into the code we have a below code,
o While scaffolding at last we need to write as -OutputDir Models
-force.
One-to-Many Relation:
In relational database, a one-to-many relationships means that one
record in a table is related to many records in another table.
This is a fundamental concept in database design where the foreign
key in child table references the primary key of parent table to
establish the relationship.
18/10/2024
Many-to-Many Relation:
In many-to-many relationship in each record from one table can
related to many records in another table and vise-versa.
It is commonly used in databases to model scenarios where entities
from two different tables are linked with multiple connections between
them.
In many-to-many actually internally works one-to-one relation.
22/10/2024
How To Create a Project in GitHub:
Open Visual Studio.
Create Project for example, Web Api.
In bottom of Vs Code, Click on “Add to Source Control” select Git.
Give Repository name and click on “Create and Push”.