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.
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.
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:
After that, in the Package Manager Console, run the following commands.
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:
Finally our project looks like the following.
Run Student.aspx file as view in browser and it will produce the following output.