Unit-4 Net Core Framework
Unit-4 Net Core Framework
Prepared By:
Dr. Suchita Patel
Assistant Professor
M.Sc. (IT) Department, ISTAR
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.
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.
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.
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.
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.
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:
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.
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.
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:
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:
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.
****************