Javatpoint Logo
Javatpoint Logo

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.

  1. Create an ASP.NET Web Application
  2. ASP Model building 1
  3. Select Template
  4. Select Template as Web Forms and change authentication as individual user account.

    ASP Model building 2
  5. Create a Master Page
  6. Create a new web form with master page template. We will use this master page to display Model data.

    ASP Model building 3
  7. Create a Data Model and Database
  8. 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.

ASP Model building 4

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.

  • Add Test data in Configuration file
  • 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

    ASP Model building 5

    Now, a database has been created and added to the project under App_Data folder.

  • Display Data
  • 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.

    ASP Model building 6

    Output:

    Run Student.aspx file as view in browser and it will produce the following output.

    ASP Model building 7





    Youtube For Videos Join Our Youtube Channel: Join Now

    Feedback


    Help Others, Please Share

    facebook twitter pinterest

    Learn Latest Tutorials


    Preparation


    Trending Technologies


    B.Tech / MCA