ASP.NET Web Forms Data Access Options

In an ASP.NET Web Forms application, you use data-bound controls to automate the presentation or input of data in web page UI elements such as tables and text boxes and drop-down lists. The process of automating data transfer between a database or other data store and a data-bound control is called data binding, and three data-binding methods are available: data source controls, model binding, and manual data binding. ASP.NET Web Forms also includes Dynamic Data Scaffolding, which is a framework that can automatically generate web pages with all of the UI needed for displaying and editing data in a database. This topic provides recommendations and guidelines for choosing the data-bound controls and data-binding method that best fit your scenario. The topic contains the following sections:

  • Data-Bound Controls

    • Controls for Displaying Lists

    • Controls for Displaying a Single Record

    • TemplateField, BoundField, and DynamicField Controls

    • DynamicControl Control

  • Data Source Controls

  • Model Binding

  • Manual Data Binding

  • Data-Binding Expressions

  • Dynamic Data Project Templates

Data-Bound Controls

ASP.NET provides an assortment of server controls that automate the process of rendering UI in markup sent to the browser. These controls provide a variety of properties that you can set to configure the appearance of the generated UI, and they raise events that you can handle in server code. For example, the following markup is all you need to write in order to generate a table like the one that is shown after the markup:

GridView markup

GridView example

Data-bound controls provide many properties that you can set in order to configure their appearance or behavior. Some of the controls also let you specify how the control generates HTML by using templates. A template is a block of HTML markup that you write and in which you include special variables that specify where and how the bound data is to be displayed. When the control is rendered, the variables are replaced with actual data and the HTML is rendered to the browser. For example, the following markup for a templated control generates the table that is shown after the markup:

ListView markup

ListView example

ASP.NET Web Forms provides many controls that you can bind to a data source, and in most cases the choice of which one to use is obvious. To create a text box you use a TextBox control, and to create a drop-down list you create a DropDownList control, and so forth. You can see what controls are available in the Standard and Data sections of the Visual Studio Toolbox window. For more information about data-bound controls, see Data-Bound Web Server Controls.

For displaying a list or table of data, or for displaying the details of an individual record, there are multiple options. The following sections explain how to choose the option that best fits your scenario.

Controls for Displaying Lists

You have several choices if you want to create a list or table of data:

  • Use the ListView control when you want to customize the generated HTML, and you also want some advanced features such as paging, sorting, grouping, and updating. The disadvantage of this control compared to the GridView control is that you have to write the HTML yourself.

  • Use the Repeater control when you want to customize the generated HTML, and efficient performance is more important than advanced features. The Repeater control is simpler and has less overhead than the ListView control. It does not support advanced features such as paging, sorting, grouping, and updating. It also does not support an empty data template. (An empty data template provides an easy way to write markup for scenarios where the data source might not return any data.) As is true of the ListView control, you have to write all of the HTML.

  • Use the GridView control for all other scenarios. This control provides a wide range of properties to configure appearance and behavior, and it can automate sorting, paging, and updating. You can let it generate all of the HTML automatically, or you can use templates to specify parts of the generated HTML manually. For some of its functions the GridView control might use view state heavily enough to cause performance degradation. In those scenarios you may be able to get better performance from the ListView or the Repeater control, at the expense of having to write more markup manually.

  • Don't use the DataList and DataGrid controls. These are legacy controls that are superseded by the GridView control.

Controls for Displaying a Single Record

Two controls are intended for use when you want to display or update the field values of a single record:

  • Use the DetailsView control when it is more important to minimize the amount of markup you have to write than it is to be able to customize the generated HTML.

  • Use the FormView control when you want to customize the generated HTML and you can afford the extra time it takes to write all of the markup manually.

You can use EntityTemplate and DynamicEntity controls in the FormView control templates to generate some of the markup automatically, thereby combining the markup generation benefits of the DetailsView control with the flexibility of the FormView control. However, there is a limited amount of documentation that shows how to do this. For more information, see Dynamic Data Templates For C# WAP or WebSite and Dynamic Data Templates For VB WAP or WebSite.

TemplateField, BoundField, and DynamicField Controls

When you use the GridView and DetailsView controls, you can let the control generate columns (GridView) or rows (DetailsView) automatically, or you can specify how they are generated yourself. If you specify them yourself, you can write your own markup in TemplateField controls or you can use BoundField or DynamicField controls. The following example shows a GridView control that displays three LastName columns, using a different method for each column:

DynamicField, BoundField, and TemplateField markup

GridView with 3 LastName columns

When the user clicks the Edit link, text boxes are displayed.

Here are some guidelines for choosing the right control for your scenario:

  • Use the TemplateField control when you need to customize the UI that is generated. For example, in display mode you might want to display the first name and last name in a single field separated by a comma, while in edit mode you might want to display two text box controls.

  • Use the DynamicField control when you're binding to strongly typed data and the default UI element for the bound data type meets your needs. The DynamicField control automatically formats the output in display mode and dynamically adds the appropriate validation controls in edit mode, based on the data type and any DataAnnotations attributes you have in your data model. For information about binding to strongly typed data, see Data-Binding Expressions later in this topic.

  • Use the BoundField control when you're binding to weakly typed data and the default UI meets your needs. For example, if the list control is bound to a SqlDataSource control, it is getting weakly typed data. The BoundField control is an earlier version of the DynamicField control that does not provide automatic formatting and validation. You get server validation with both controls, but you get automatic validation on the client only with the DynamicField control.

DynamicControl Control

When you use TemplateField controls in the GridView and DetailsView controls, and when you write markup for FormView and ListView templates, you can specify UI elements such as Label and TextBox controls as shown in the previous example, or you can use DynamicControl controls. Like DynamicField controls, DynamicControl controls automatically format and validate based on DataAnnotations attributes in your data model. The following example shows them used to display last name, first name, and hire date fields all in one table column:

DynamicControl sample code

DynamicControl example

If Label and TextBox controls had been used in this example instead of DynamicControl controls, the DateTime value of the hire date would have been displayed with the time, for example: 3/11/1995 12:00:00 AM. But the HireDate field includes a DataAnnotations attribute that specifies its format, and the DynamicControl uses this information:

HireDate field with DataAnnotations attributes

As in the case of the DynamicField control, choose the DynamicControl control in data-bound control templates when you're binding to strongly typed data, unless the UI that it creates is not what you want.

For more information about how to use the DynamicField and DynamicControl controls, see the following resource:

  • Using Dynamic Data Functionality to Format and Validate Data (ASP.NET site. Shows how to use DynamicField controls with data source controls. The code that this tutorial puts in the Page_Init handler in order to enable dynamic data functionality is not necessary when you use model binding as your data binding method. Model binding automatically enables dynamic data functionality. For more information about model binding, see Model Binding later in this topic.)

Data Source Controls

Data source controls are controls that you put on a web page in order to specify the link between a data source and UI server controls. You typically create data source controls by including markup in an .aspx page, but they do not render any UI; their only purpose is to link data-bound controls to a data source. In the following example, a SqlDataSource control specifies the connection string and SQL select command, and the GridView control specifies the data source control that it uses to get data:

SqlDataSource control markup

Data source controls are a good choice of data binding method if you don't want to write code to handle data access or you're using rapid application development (RAD) methodology in order to get an application up and running in a minimum amount of time. Data source controls enable you to create a web application that offers basic insert, read, update, and delete functionality without writing any code at all. However, the declarative model for specifying data access functions has limited flexibility. Most real-world applications have relatively complex needs for tasks such as data validation and exception handling that may require that you write code anyway. And code that you write in order to make data source controls handle scenarios they weren’t specifically designed for is often cumbersome. For any application that needs more than the most basic read-write functionality, consider using model binding instead of data source controls.

The specific data source control you use depends on the technology you choose for database access:

  • Use the SqlDataSource control when you want to use ADO.NET directly and write your own queries.

  • Use the EntityDataSource control for data that you access by using the Entity Framework. For information about how to use this control with current releases of the Entity Framework, see How to use the EntityDataSource control with the DbContext API.

  • Use the XmlDataSource control for XML data that you have in an object in memory (that is, you're not retrieving it from a database).

  • Use the LinqDataSource control for data that you access by using the LINQ to SQL ORM.

  • In projects that target ASP.NET 4 or earlier versions, use the ObjectDataSource control when you want to write custom code for data access, such as for multi-tier application architecture. In projects that target ASP.NET 4.5, model binding is recommended instead for this scenario. For more information, see the following section.

  • Do not use the AccessDataSource control. You will find this control in the Toolbox for projects that target ASP.NET 4 and earlier versions, but Microsoft recommends against using Access in web applications. For more information, see Can my ASP.NET web application use a Microsoft Access database? in ASP.NET Data Access FAQ.

For more information, see Data Source Web Server Controls.

Model Binding

ASP.NET data source controls facilitate rapid application development, but they are inflexible. They are easy to work with for simple tasks that they were explicitly designed for, but the learning curve is steep if you need to do something special. Also, since you configure data source controls in .aspx page markup, you can't keep data access code in a data access layer, and you can't implement automated unit testing for your data access code. The ObjectDataSource control facilitates multi-tier application architecture and unit testing, but handling many common scenarios like two-way data-binding and input validation can be cumbersome.

In ASP.NET 4.5, Web Forms model binding addresses these issues. The model binding pattern was first introduced with ASP.NET MVC and was subsequently adapted for ASP.NET Web Forms. You write code for insert, read, update, and delete methods, and you specify in the markup of the data-bound control which methods it should call for each operation. The framework minimizes the amount of code you have to write for common data access operations, and since you're writing your own code there is no steep learning curve when you need to do something special.

In the following example, the GridView control specifies the methods to call to read a list of instructors and to update an instructor when the user clicks an Edit link:

GridView control using model binding

You can also specify Insert and Delete methods, and you can add validation controls to display error messages. The following example shows the methods identified by the SelectMethod and UpdateMethod attributes in the preceding example:

public IEnumerable<Instructor> GetInstructors()
{
    List<Instructor> instructors;
    using (var db = new SchoolContext())
    {
        instructors = db.Instructors.Include("Courses").ToList();
    }
    return instructors;
}

public void UpdateInstructor(int personID)
{
    using (var db = new SchoolContext())
    {
        var instructor = db.Instructors.Find(personID);
        if (instructor == null)
        {
            ModelState.AddModelError(String.Empty, String.Format("An instructor with ID {0} could not be found.", personID));
            return;
        }
        TryUpdateModel(instructor);
        if (ModelState.IsValid)
        {
            db.SaveChanges();
        }
    }
}

When the data-bound control needs to retrieve or update data, ASP.NET calls the appropriate method that you have identified, and in the method parameters ASP.NET automatically provides data received from the client in form fields, cookies, or query strings. In this example, the UpdateInstructor method automatically receives the ID value of the record to be updated because the GridView control specifies PersonID in the DataKeyNames attribute. And the TryUpdateModel method automatically updates the properties of the instructor object based on input received from the web page.

If your Select method returns an IQueryable object, the GridView control can automatically provide advanced functions such as paging and sorting.

In new development that targets ASP.NET 4.5, use model binding instead of data source controls unless all of the following conditions are true:

  • You want to avoid writing code.

  • Your application requires very basic read-write functionality. (It doesn’t need complex validation logic, custom exception handling, etc.)

The reason for the second condition is that real-world applications typically include functionality that you have to write code for even with data source controls, and in that case the code that you write for model binding would typically be less cumbersome.

Model binding is still relatively new and the amount of documentation written for it is minimal compared to what is available for data source controls. More in-depth model binding documentation is currently being developed.

In applications that target earlier versions of ASP.NET earlier than 4.5, you can't use model binding. For n-tier architecture, unit testing, and customizing data access, the alternative is to use the ObjectDataSource control.

For more information about Web Forms model binding, see ASP.NET Data Access Content Map.

For a tutorial series on using model binding with Web Forms, see Model Binding and Web Forms.

Manual Data Binding

Data source controls and model binding do much of the data binding work in order to make you more productive, but in some scenarios you might want to manually set a data-bound control's DataSource property and call its DataBind method.

In applications that target ASP.NET 4 or earlier versions, this data-binding method is typically used when you want to bind a control to an in-memory collection instead of a database or data service. For example, the following code constructs an in-memory collection and binds it to a DropDownList control. The markup for the drop-down list control is shown after the data-binding code.

protected void Page_Load(object sender, EventArgs e)
{
    var instructors = new List<Instructor>();
    instructors.Add( new Instructor() { PersonID = 1, LastName="Abercrombie" });
    instructors.Add( new Instructor() { PersonID = 2, LastName="Zheng" });
    InstructorsDropDownList.DataSource = instructors;
    InstructorsDropDownList.DataBind();
}

DropDownList for manual data binding example

In ASP.NET 4.5, you can handle scenarios like this more easily by using model binding and constructing the collection in a Select method. There are few scenarios in ASP.NET 4.5 where you would want to do manual data binding instead of model binding. One exception is for asynchronous data access, when you need to call a DataBind method in a callback handler.

Data-Binding Expressions

For templated data-bound controls, you write markup that indicates where values from each data field should be displayed, or which UI elements such as text boxes update which data fields. To do that you use data-binding expressions. For weakly typed data, you can use the Eval (for display only) and Bind (for display and update) expressions. The following example shows an Eval expression in a template that is used for display only, and a Bind expression in a template that is used for updating:

GridView using Eval and Bind

Eval and Bind expressions are not strongly typed; that is, the type of the expression is not known at design time. This means you don't get IntelliSense at design time or validation at compile time for them. In applications that target ASP.NET 4.5 you can use the Item (display only) and BindItem (display and update) expressions for strongly typed data. To use these expressions, declare the data type of the items you're binding to the control by using the ItemType attribute, as shown in the following example:

GridView using Item and BindItem

If you're developing an application that targets ASP.NET 4.5, use the Item and BindItem expressions instead of the Eval and Bind expressions, except in the following scenarios:

  • You're providing weakly typed data to the data-bound control.

    Data source controls such as the SqlDataSource control provide weakly typed data. In some model binding scenarios, you might have to return weakly typed data from your Select method, such as a non-generic IEnumerable collection or a DataSet object.

  • The data-bound control you're using does not support strongly typed data binding.

    A few older controls that are no longer commonly used have not been updated. If the control you want to use inherits from the DataBoundControl type, it has an ItemType property and supports strongly typed data binding.

  • You're using automatic column generation in the GridView control, and you want the control to generate BoundField controls instead of DynamicField controls.

    For more information, see GridView.AutoGenerateColumns.

Data-binding expressions are contained within <%# and %> delimiters. In addition to calling Eval, Bind, Item, and BindItem methods, you can call any publicly scoped code within the <%# and %> delimiters to execute that code and return a value during page processing. In ASP.NET 4.5 you can add a colon to the opening delimiter to specify that the value of the expression should be HTML-encoded, as shown in the following example:

Adding a colon to specify HTML encoding

The additional colon was not used in the preceding examples because the Text property of a data-bound control is automatically HTML-encoded. Using the colon in scenarios like this example where the value of the expression would otherwise not be HTML-encoded is recommended to help prevent cross-site scripting attacks.

For more information about data-binding expressions, see ASP.NET Data Access Content Map.

Dynamic Data Project Templates

Visual Studio includes project templates for creating dynamic data web applications. In ASP.NET 4.5, you must use the Entity Framework to access your database. (For applications that target ASP.NET 4, you can also use LINQ to SQL.) At run time, the dynamic data run-time scaffolding feature uses information about the database contained in the data model to determine how to display each table and each column within a table. The scaffolding feature also determines how to validate input entered in a web page to be stored in each table column.

Dynamic data run-time scaffolding is a good alternative to writing markup and code for data access manually when the following conditions are true:

  • You need to quickly create an application that gives its users the ability to view and update data in a database.

  • The application needs minimal business logic beyond basic create, read, update, and delete functionality, and you don't expect that to change in the future.

  • The application needs minimal customization of the default UI for each data type, or customization is required and you're prepared to invest time in learning how to customize dynamic data templates.

  • The application will be hosted on an internal network, and anyone who has access to the application can be granted access to all of the data that it makes available. It is difficult to configure fine-grained security restrictions for a Dynamic Data application.

The development of dynamic data scaffolding led to many advances in data handling in ASP.NET Web Forms, MVC, and Web Pages. Features such as automated display formatting and input validation based on data types and DataAnnotations attributes are no longer limited to dynamic data run-time scaffolding projects. Microsoft continues to develop data handling features built on dynamic data technology for ASP.NET. However, like LINQ to SQL, dynamic data run-time scaffolding is now a low priority for future development. If dynamic data run-time scaffolding features don't meet your needs now, don't create a dynamic data scaffolding application in expectation that the features you need will be added in the future.

A disadvantage of dynamic data run-time scaffolding is the steep learning curve for customizing how data is displayed and validated. Future development efforts are focused on technologies that offer similar benefits while making it possible for you to customize web application behavior by using skills and knowledge that you already have from working with ASP.NET.

For more information about Dynamic Data Scaffolding, see ASP.NET Dynamic Data.

Options

Recommended Choice(s)

More Information

Web Forms list controls

  • To customize generated HTML, with advanced features: ListView control

  • To customize generated HTML, when read-only access is sufficient and efficiency is more important than advanced features: Repeater control

  • For maximum automation of HTML generation: GridView control

Controls for Displaying Lists

Web Forms single-record controls

  • To customize generated HTML: FormView control

  • For maximum automation of HTML generation: DetailsView control

Controls for Displaying a Single Record

Web Forms field controls for GridView and DetailsView controls

  • For strongly typed data: DynamicField control

  • For weakly typed data: BoundField control

  • To customize column or row appearance: TemplateField control

TemplateField, BoundField, and DynamicField Controls

Web Forms data-bound controls for templates in ListView, Repeater, FormView, and TemplateField controls

  • For strongly typed data: DynamicControl control

  • For weakly-typed data: specific UI controls

DynamicControl Control

Web Forms data binding methods

  • When you don't want to write any code, and data access requirements are simple: data source controls

  • For all other scenarios when it is feasible to write code for data retrieval and update: model binding

  • For controls that don't support model binding, and when you need control over the timing of data binding (for example, for asynchronous data retrieval): manual data binding

Data Source Controls

Model Binding

Manual Data Binding

Data-binding expressions

  • For weakly typed data: Eval and Bind

  • For strongly typed data: Item and BindItem

  • Use the colon in the opening delimiter for data-binding expressions (<%#:) to enable automatic HTML-encoding.

Data-Binding Expressions

Dynamic Data project templates (when to use)

Use in the following scenario:

  • You have to create a database application rapidly.

  • The application requires minimal business logic.

  • The application requires minimal UI customization, or you're prepared to invest time in learning how to customize dynamic data templates.

  • The application will be deployed on an internal network and does not need fine-grained security restrictions.

Dynamic Data Project Templates

See Also

Concepts

ASP.NET Data Access Options

Other Resources

ASP.NET Data Access Content Map