0% found this document useful (0 votes)
4 views36 pages

Unit-4 Net Core Framework

The document provides an overview of Model Binding in ASP.NET Core MVC, explaining how HTTP request data is automatically mapped to action method parameters or model properties. It discusses the use of IFormCollection for manual data extraction, its limitations, and the advantages of using Model Binding with strongly typed models. Additionally, it covers CRUD operations using Entity Framework Core, detailing project setup, model definition, database connection configuration, and the role of DbContext in managing database interactions.

Uploaded by

suchitab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views36 pages

Unit-4 Net Core Framework

The document provides an overview of Model Binding in ASP.NET Core MVC, explaining how HTTP request data is automatically mapped to action method parameters or model properties. It discusses the use of IFormCollection for manual data extraction, its limitations, and the advantages of using Model Binding with strongly typed models. Additionally, it covers CRUD operations using Entity Framework Core, detailing project setup, model definition, database connection configuration, and the role of DbContext in managing database interactions.

Uploaded by

suchitab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

CVM UNIVERSITY

INSTITUTE OF SCIENCE & TECHNOLOGY FOR ADVANCED STUDIES & RESEARCH


(ISTAR)
M.Sc. (Information Technology)
Semester – II

Paper Code: 101410212


Paper Title: .NET CORE FRAMEWORK

Prepared By:
Dr. Suchita Patel
Assistant Professor
M.Sc. (IT) Department, ISTAR

Unit 4: Model Binding: Html Form behaviour; Model Binder Overview;


DefaultModelBinder; Binding to Complex Classes ; IFormCollection Model
Binding; IFormFile Model Binder; Bind Attribute ; TryUpdateModelAsync;
State Management Techniques: Cookies; Session Security: Authentication
and Authorization MVC and Entity Framework Core: Basic CRUD
Operations using Entity Framework
Model Binding in ASP.NET Core MVC

Model Binding in ASP.NET Core MVC is the process by which HTTP request
data (like form data, route data, query strings, and headers) is
automatically mapped to action method parameters or model properties.
The action method parameters can be simple types like integers, strings,
etc., or complex types such as Student, Order, Product, etc.

When a request is made to an MVC application, the data sent from the client
is often in a format (such as query strings, form data, and route data) that
needs to be converted into .NET objects. Model Binding simplifies this
process by handling this conversion automatically, allowing developers to
work with strongly typed models instead of raw HTTP data.

Example Without Using Model Binding in ASP.NET Core MVC


Let us first understand one example without using Model Binding, i.e., how
to capture request data in an ASP.NET Core MVC Application without
Model Binding. In ASP.NET Core MVC, we can use the IFormCollection
interface to extract data manually from HTTP requests.

What is IFormCollection in ASP.NET Core MVC?


IFormCollection is an interface in ASP.NET Core MVC that represents a
collection of form data submitted in an HTTP POST and PUT requests. It
provides access to form fields and their values, allowing developers to
work with the form data directly. The form fields are stored as key-value
pairs, where the key is the field name, and the value is the field value(s). It
provides the following methods and properties to retrieve form values:

Keys – Retrieves all the keys in the form collection. It will hold all the form
field names.
ContainsKey(key) – Determines if a specific key is present in the form
collection.
TryGetValue(key, out value) – Attempts to get the value associated with a
specific key.

The IFormCollection can be used as a parameter in an action method to


access form data directly without binding each form field to a model
property.
Example using IFormCollection in ASP.NET Core MVC
Let’s understand how to use IFormCollection to fetch data from HTTP
Requests. First, create a new ASP.NET Core MVC Application
named ModelBindingDemo. Then, modify the HomeController as
follows. As you can see, we are using IFormCollection as a parameter to
capture the form data using the controller action method.
Modifying the Index View:
Next, modify the Index.cshtml view as follows:

Now, run the application and access the Index page. It should open on the
following page. Provide the User Name and Email address and click on the
Submit button as shown in the below image:
Limitations of IFormCollection in ASP.NET Core MVC
The following are the limitations of IFormCollection in ASP.NET Core MVC:
 Limited to Form Data Only: IFormCollection can only handle form
data submitted via POST requests. It cannot be used to access data
from other sources, such as query strings, route data, or JSON bodies.
 No Strong Typing: The data in IFormCollection is accessed via key-
value pairs, meaning you lose the benefits of strong typing. You need
to manually cast or convert the data to the desired types, which can
lead to errors if the conversion fails.
 Lack of Validation: IFormCollection does not automatically validate
the data. You must manually check for required fields, data types, and
other validation rules, increasing the risk of errors.
 Scalability Issues: For large and complex forms, manually extracting
and processing each form field using IFormCollection can become
difficult, time-consuming, and less maintainable. As the number of
fields increases, the code becomes more error-prone and harder to
manage.
 Manual Data Handling: With IFormCollection, we need to handle
data conversions, null checks, and errors manually. Model binding
handles this automatically, making our code cleaner and easier to
maintain.
 No Built-in Security Checks: IFormCollection does not inherently
provide security features like anti-forgery token validation, which are
more easily integrated when using model binding with view models.

Example Using Model Binding in ASP.NET Core MVC


Let’s see how we can rewrite the previous example using Model Binding in
ASP.NET Core MVC. First, let’s create a model to hold the UserName and
UserEmail data, which will be submitted from the form. So, create a class
file with the name User.cs within the Models folder and copy and paste the
following code. We are making the UserName and Email field mandatory
using the [Required] data annotation attribute.

Next, modify the Index.cshtml view as follows. As you can see, the User is
now the model for the following view. Here, we are using Tag Helpers to
Create the form and input elements.
Next, modify the HomeController as follows:
Now, run the application, and it should work as expected. Once you access
the Index Page, the following form will be displayed: Provide the User
Name and Valid Email address and click on the Submit button, as shown in
the image below.
Now, click the Submit button without Providing the User Name and Email
address. You should see the Validation Error messages as shown in the
image below:
How Does Model Binding Work in ASP.NET Core MVC?
Model binding in ASP.NET Core MVC works by inspecting the parameters of
the action method and then looking through the sources of the request data
(like form values, route data, query string parameters, etc.) to find matches.
It uses various binders for different types of data.

For example, simple types like int and string can be bound from route data
or the query string, while complex types are typically bound from form
values or JSON body data. The model binder is also responsible for
validation based on data annotations or custom validators applied to the
model properties. So, Model Binding in ASP.NET Core MVC works as
follows:
 Determine the Binding Source: ASP.NET Core MVC first determines
the source of the data based on the action method’s parameters.
Depending on the source attribute (e.g., [FromQuery], [FromBody],
[FromRoute]), it knows where to look, such as in the query string, the
request body, or the route data.
 Fetch Data from the Source: The framework retrieves the data from
the identified sources.
 Match and Convert Data: The model binder matches the data with
the action method parameters or model properties. If the names
match, the data is converted to the appropriate type.
 Bind Data to Parameters or Models: The converted data is then
bound to the parameters or properties.
 Handle Errors: If binding fails (e.g., due to a type mismatch), the
model binder may add errors to the ModelState dictionary, which can
be used to handle validation errors in the application.

Different Model Binding Techniques in ASP.NET Core MVC:


You can configure model binding using various attributes that control how
data is extracted from the request. Some common attributes include:
 [FromBody]: This attribute tells ASP.NET Core to bind data from the
request body to the parameter of an action method. It’s commonly
used when complex types like objects or collections, typically in JSON
or XML format, are expected in the body of a POST request. It is
commonly used in Restful Services.
 [FromForm]: The [FromForm] attribute binds data from HTML
form fields to action method parameters. It’s suitable for handling
form submissions via HTTP POST or PUT requests and is commonly
used in ASP.NET Core MVC Applications.
 [FromQuery]: Binds data from the query string of the URL to action
parameters. The [FromQuery] attribute binds data from the URL’s
query string to action method parameters. It’s often used in HTTP
GET requests where data is passed in the URL as Query String
Parameters.
 [FromRoute]: The [FromRoute] attribute binds data from route
parameters to action method parameters. Route parameters are
placeholders in the URL defined in your route templates.
 [FromHeader]: It helps extract custom or standard headers, such as
Authorization, User-Agent, etc. This is often used
CRUD Operations in ASP.NET Core MVC using Entity Framework Core

CRUD (Create, Read, Update, Delete) operations are fundamental for most
web applications, and ASP.NET Core MVC with Entity Framework Core
provides a streamlined approach for implementing these operations.
Let us see one real-time example of performing database CRUD operations
in an ASP.NET Core MVC Application using Entity Framework Core with
multiple database tables. Let us create one complete example of managing
employees and departments in an organization. In this example, we will use
ASP.NET Core MVC, Entity Framework Core Code First Approach, and SQL
Server Database.

Step 1: Project Setup


Create a New ASP.NET Core MVC Project: Open Visual Studio. Create a new
project (CRUDinCoreMVC) and select the ASP.NET Core Web App (Model-
View-Controller) template.

Install The Packages: Once you have created the Project, as we are going to
work with the SQL Server Database, we need to install the following two
NuGet Packages, which are required for Entity Framework Core:

Microsoft.EntityFrameworkCore.SqlServer:
This package is the Entity Framework Core database provider for Microsoft
SQL Server and Azure SQL Database. It is necessary for any ASP.NET Core
application that intends to use these databases. The primary functions of
this package include:

 Database Connection: It allows EF Core to establish connections to a


SQL Server database.
 SQL Generation: It translates the LINQ queries from your application
into SQL queries that the SQL Server can understand.
 Schema Generation: It is responsible for translating the entity data
models into SQL Server database schemas. This is particularly useful
when creating and migrating databases.
 Optimizing Performance: The package includes SQL Server-specific
optimizations, enhancing the performance of data access operations.

Microsoft.EntityFrameworkCore.Tools:
This package provides additional tools for working with Entity Framework
Core, which is especially useful during development. These tools enhance
the development experience and simplify many database-related tasks. Key
features include:
Migrations: Commands for creating and managing migrations are included,
which help evolve the database schema over time without losing data.
Database Update: This tool allows applying migrations to update the
database schema directly from the command line or via the Package
Manager Console in Visual Studio.
Database Scaffolding: It can reverse engineer a database schema to create
entity model classes and a DbContext based on an existing database, which
is particularly useful in database-first scenarios.
Script Generation: Generate SQL scripts from migrations, which can be
useful for manual reviews or when deploying databases through scripts
You can install the above two Packages using NuGet Package Manager for
Solution or by using Package Manager Console. Please execute the
following command using the Package Manager Console to install the
Packages.
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Your project structure should look like the one shown below after Step 1.
However, your package might be different when you read this article.

Step 2: Define Models


Next, we need to define the models according to our application’s data
structure. As we will manage the Employee and Department data, let’s
define two models: Employee and Department. So, create a class file
named Department.cs within the Models folder and then copy and paste
the following code:
Create another class file named Employee.cs within the Models folder, and
then copy and paste the following code:

By default, we have implemented one-to-many relationships between


Employees and Departments. An employee belongs to a single department,
and one department can have many employees.

Step 3: Configure the Database Connection


Instead of hard-coding the connection string with the DbContext class, we
will store the connection string in the appsettings.json file. So, add your
database connection string in the appsettings.json file as follows:

Step 4: Configure DbContext


Create a DbContext class for the application to manage the database. In
Entity Framework Core (EF Core), the DbContext class is the component
that serves as a bridge between your application’s code and the database. It
plays an important role in managing the interactions with the underlying
database in an efficient and performance-oriented manner. So, add a class
named EFCoreDBContext.cs and then copy and paste the following code.

Role of DbContext in EF Core:


 Querying: DbContext provides the necessary methods and
properties to query the database. It converts LINQ (Language
Integrated Query) expressions into SQL queries that the database can
understand.
 Saving Changes: It tracks changes made to objects and applies them
to the database when SaveChanges() or SaveChangesAsync() is
called. This includes translating the changes into insert, update, or
delete commands.
 Model Mapping: It maps classes to database tables and properties to
table columns through the ModelBuilder class used in the
OnModelCreating method.
 Change Tracking: DbContext tracks entities’ states during their
lifecycle. This tracking ensures that only actual changes are updated
in the database during a save operation, which helps optimize
database access and improve performance.
Step 5: Configure the Database Connection:
Next, we need to configure the connection string with the DbContex class.
Please add the following code to the Program class. The following code
configures the DbContext in an ASP.NET Core application using Entity
Framework Core (EF Core).

Code Explanation:
builder.Services: builder.Services refer to the IServiceCollection provided
by the ASP.NET Core host builder. This collection registers services that the
application will use, including platform features like MVC, logging, DI
containers, and more.

AddDbContext<EFCoreDbContext>: The AddDbContext is an extension


method provided by EF Core that registers the DbContext as a service in the
DI (Dependency Injection) container. In this case, it’s registering
EFCoreDbContext. This method also ensures that the lifecycle of the
DbContext is managed correctly, typically as a scoped service. This means a
new instance of the DbContext is created for each request.

Lambda Configuration (options => …): The lambda expression is used to


configure options for the DbContext. These options control how the
DbContext behaves and interacts with the underlying database.

options.UseSqlServer: UseSqlServer is a method that specifies SQL Server


as the database provider for EF Core. This method also tells EF Core to
translate the LINQ queries and other data operations into SQL that is
compatible with SQL Server.

builder.Configuration.GetConnectionString(“EFCoreDBConnection”):
builder.Configuration provides access to the application’s configuration,
typically including settings from files like appsettings.json, environment
variables, and other configuration sources. GetConnectionString is a
method that retrieves a connection string by its key
(“EFCoreDBConnection” in this case) from the application’s configuration.
This connection string contains the necessary information for connecting to
the SQL Server database (like server address, database name, credentials,
etc.).
Step 6: Database Migration
Next, we need to generate the EF Core migrations and update the database
schema. Open the Package Manager Console and Execute the add-migration
and update-database commands as follows. You can give your migration
any name. Here, I am giving it EFCoreDBMig1. The name you are giving it
should not be given earlier.

With this, our Database with Departments and Employees table is created,
as shown in the below image:

Before proceeding and performing the database CRUD Operations, let us


first insert some master data into the Departments database table by
executing the following INSERT SQL statements, which we will use while
performing the Employee CRUD operation.
Step 7: Creating EmployeesController to Perform CRUD Operations Using
EF Core:
Next, create an Empty MVC Controller
named EmployeesController within the Controllers folder. Here, I am
going to Scaffold Controllers and Views, which will automatically generate
the Actions and Views using the Entity Framework Core for us to perform
the CRUD Operations. Later, we will modify the auto-generated actions and
views as per our requirements. Please follow the below steps to Scaffold
Controllers and Views.
Right-click on the Controllers folder and then select Add =>
Controller from the context menu, which will open the following Add New
Scaffold Item window. Here, please select MVC Controller with views,
using Entity Framework option and then click on the Add button as
shown in the image below:

Once you click on the Add button, the following window will open. Here,
provide the Model Class as Employee, provide the DbContext Class as
EFCoreDBContext, Keep the rest of the setting for Views as it is, provide
the Controller name as EmployeesController, and then click on
the Add button as shown in the below image:
Once you click the Add button, it will take some time to create the
controller, all the action methods to perform the database CRUD
Operations, and the corresponding views for us. The following is the auto-
generated Employees Controller class:
Now, if you verify the Views folder, then you will see the views for the
Employees controller as shown in the below image:

Note: The Scaffolded Controllers will contain methods for CRUD


operations. As we progress, we will customize these methods and views, as
per our application requirements.

Creating Department Controller:


The way we have created the EmployeesController, in the same way, we
can also create the DepartmentsController. So, please follow the same steps
and create the Departments Controller. While creating the Controller, you
must provide the Model class as Department.

Testing
Run the application and test all CRUD operations for both employees and
departments. Ensure that the department selection works correctly when
creating or editing an employee. Before testing, first, modify the Default
controller and action to Employee and Index in the Program class as
follows:

Now, if you run the application and go to the Employees/Create URL, you
will see it displays the Department ID in the Drop-Down List instead of the
Department name, as shown in the image below.
To display the Department name instead of ID, modify the Create Action
Method (both Get and Post) of the EmployeesController as follows:
Now, run the application and navigate to the Employees/Create URL, and
you should see it showing the Department name in the dropdown list. Let
us create one employee and click the Create button, as shown in the image
below.

Once you click on the Create button, the new employee will be added to the
database. Then, it will redirect you to the Index page, which will display all
the Employees, as shown in the image below. We have created only one
employee, and that employee’s information will be displayed here.

If you look at the Index view, it is showing the Department as 2. So, instead
of showing the Department ID, we need to show the Department name. To
do so, modify the Index view of the Employees controller as follows:
Now, run the application, and it should display the Department name in the
Index view as shown in the below image:
To see the Employee details, click the Details button as shown in the above
image. Once you click on the Details button, it will open the following
Details view.

As you can see, the Department ID is also displayed here. To show the
Department name instead of the Department ID, please modify the Details
view of the Employee controller as follows:
Now, run the application and see the Details of the Employee and it should
show the Department name as expected, as shown in the image below:
Now, click the Edit button either from the Details view or Index view to edit
an employee. Once you click the Edit button, the following view with
prepopulated employee information will open.
Further, if you notice, it shows the Department ID in the Dropdown List.
Instead of showing ID, if you want to show the Name of the Department,
then please modify the Edit action method (both Get and Post) of
the Employees controller as follows:
Now, it should display the Department Name in the dropdown list. Let us
modify the Employee Department to IT and Position to DBA and click the
Save button, as shown in the image below.

Once you update the data and click on the Save button, it will save the data
into the database and redirect to the Index view, where you can see the
updated data, as shown in the image below.

Now, click the Delete button, as shown in the above image, to Remove the
Employee from the database. Once you click the Delete button, the
following Delete View will open.
As you can see in the above image, it is showing the Department ID value
instead of the Department Name. To display the Department Name, modify
the Delete view of the Employees controller as follows:
With the above changes, run the application, go to the Index View, and click
the Delete button. This time, it should display the Department Name
instead of the Department ID, as shown in the image below. Click on
the Delete button to delete the Employee from the database.
Once you click the Delete button, it will delete the employee and then
navigate to the Index view.
While creating and updating an employee, the dropdown list name is
displayed as DepartmentId. If you want to display Department Name
instead of DepartmentId, modify the Employee model as follows. Here, you
can see we are decorating the DepartmentId property with a Display
Attribute and setting the Name Property as Department Name.

Note: Similarly, you can test the Department Controller and Views and
Perform the database CRUD Operations.
Enhancements
As per your business requirements, you can make the following
enhancements:
 Validation: Implement data annotations for model validation.
 Exception Handling: Include proper error handling in your
application.
 User Interface: Use CSS and JavaScript to improve the UI.
 Advanced Features: Consider adding features like search, sorting,
and pagination.

****************

You might also like