ASP.NET Web Forms Model Binding
This topic explains How to work with data using Model Binding and Web Forms. Model binding makes data interaction more straight-forward than dealing with data source objects such as ObjectDataSource or SqlDataSource.
In this tutorial, we will use Entity Framework for data and GridView to display data on the web page. Here, we are creating an example that includes the following steps.
- Create an ASP.NET Web Application
- Select Template
- Create a Master Page
- Create a Data Model and Database
Select Template as Web Forms and change authentication as individual user account.
Create a new web form with master page template. We will use this master page to display Model data.
We will use Code First Migrations to create objects and the corresponding database tables. These tables will store information about the students and their courses.
Create a new model class in Model folder.
// StudentModels.cs
The SchoolContextDemo class derives from DbContext, which manages the database connection and changes in the data.
We will use the tools for Code First Migrations to set up a database based on these classes. Open Package Manager Console from the menu bar by following view->other windows-> Package Manager Console.
It will prompt a screen at bottom of the Visual Studio IDE. We need to execute the following command in this console.
After executing the above command, it produces the following output.
After that a new file named Configuration.cs has been created. This file is automatically opened after it is created. This class contains a Seed method that enables us to pre-populate the database tables with test data.
Here, we will add some data to the configuration file that we can show to the user at web page. After adding data into the file, our Configuration.cs file looks like this:
// Configuration.cs
After that, in the Package Manager Console, run the following commands.
And
Now, a database has been created and added to the project under App_Data folder.
Now, let’s display the data to the web page from the database we created. We will use GridView control to display the data in grid form. The Student.aspx file looks like this:
// Student.aspx
Code Behind
// Student.aspx.cs
Finally our project looks like the following.
Output:
Run Student.aspx file as view in browser and it will produce the following output.