Language

ASP.NET Scaffolding with Web Forms

By |

This topic demonstrates how to use the new ASP.NET Scaffolding feature in ASP.NET Web Forms application. Using scaffolding, you can automatically generate much of the boilerplate code for modifying and presenting data in a web page. This feature is part of the Preview release for Visual Studio. More enhancements will be made to ASP.NET Scaffolding in future releases. For notes and workarounds, see Known Issues.

For an example of using scaffolding in an MVC project, see Getting Started with ASP.NET MVC 5.

What you'll build

In this tutorial, you'll:

  • Create a model class for your data
  • Generate pages to retrieve, create, delete, and edit the data for your model
  • Enhance the presentation of the generated pages

Prerequisites

  • Microsoft Visual Studio 2013 Preview
  • Web Developer Tools (part of default Visual Studio 2013 Preview installation)

Set up project

In Visual Studio, create a new ASP.NET Web Application project called ContosoUniversity.

create project

Select the Web Forms template, and click Create Project.

select web forms

Create data model

If your project does not include a folder named Models, create one. In the Models folder, add a new class named UniversityModels.cs. In that file, define a class and enumeration as shown in the following code:

using System;
using System.ComponentModel.DataAnnotations;

namespace ContosoUniversity.Models
{
    public class Student
    {
        [Key]
        [ScaffoldColumn(false)]
        public int StudentID { get; set; }

        [Required, StringLength(40), Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required, StringLength(20), Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Range(typeof(DateTime), "1/1/2013", "1/1/3000", ErrorMessage = "Please provide an enrollment date after 1/1/2013")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        [Display(Name="Enrollment Date")]
        public DateTime EnrollmentDate { get; set; }

        [EnumDataType(typeof(AcademicYear)), Display(Name = "Academic Year")]
        public AcademicYear Year { get; set; }
    }

    public enum AcademicYear
    {
        Freshman,
        Sophomore,
        Junior,
        Senior
    }
}

The StudentID property is marked with the ScaffoldColumn(false) attribute which means the property will not be included in the data presentation code that is automatically generated when you add a scaffold.

The Display and DisplayFormat attributes enable you to specify values that are used when rendering the row or column for the property. The Required, Range, and StringLength attributes enable you to specify validation rules for the property.

Build the project.

Add scaffold

Now, you will add a scaffold to your project which will generate web pages for reading and modifying the data associated with your model. To add a scaffold, right-click your project, and select AddScaffold.

select add scaffold

In the Add Scaffold window, select the option for Web Forms pages with read/write actions using Entity Framework and click Add.

add scaffold

In the Add Web Forms Pages window, make the following selections:

  • Model class: Student
  • Data context class: Add new data context
  • Generate desktop views: Checked
  • Generate mobile views: Checked

select model class

Click Add.

You can accept the default name for the context class.

add context

Your project now includes a new folder named Student that contains web pages for the different data operations. You will also have duplicate web pages for the mobile layout.

new folder

Review automatically-generated pages

To view your new web pages, open Site.master and add a link to the default page for the Student folder. The default page includes links to the other pages.

<ul class="nav nav-pills nav-stacked">
    <li><a runat="server" href="~/">Home</a></li>
    <li><a runat="server" href="~/About">About</a></li>
    <li><a runat="server" href="~/Contact">Contact</a></li>
    <li><a runat="server" href="~/Student">Students</a></li>
</ul>

Run your application and navigate to the Students page. Notice there are no entries, but a link exists to create one. Click the Create new link.

start new

On the Insert page, you can provide values for the fields. The enumeration property is automatically rendered as a drop-down list. The other properties are rendered as text boxes. The StudentID property is not rendered because that property is marked with the [ScaffoldColumn(false)] attribute. After providing values, click the Insert button.

insert new data

The Student list now includes the new entry. The list automatically includes links for Edit and Delete.

person added

If you click Edit, you are taken to a page that enables updating the data.

edit student

If you click Delete, you are taken to a confirmation page before removing the student from the list.

delete student

Verify validation rules

The data annotation attributes that you applied to your model enforce validation rules within the new pages. On the Insert page, try submitting the form without providing any values. The required property validators are applied.

validation results

The date range that you specified for enrollment date is also applied, as shown below.

invalid date

The text boxes for first and last name do not accept more characters than the number specified in the StringLength attribute. The following image shows that the first name text box will accept 20 characters but you cannot enter more.

string limit

Review mobile pages

In Internet Explorer, open the F12 Developer Tools. Under the Tools menu item, select Change user agent string, and pick IE10 for Windows Phone 8. Refresh the page and notice the new layout. For example, the Insert page appears as follows:

mobile insert

Close the browser.

Enhance presentation

There are a couple of small enhancements you will make to the presentation. The Delete, Edit, and Insert pages all use a DynamicEntity control to render the model. The DynamicEntity control uses the names you provide in the Display attribute (for example “First Name“ instead of “FirstName”). However, the default page uses a table with the table headers set to the property names. You can change this formatting by simply changing the table headers directly. Open the Default.aspx file in the Student folder, and change the table header values.

<thead>
    <tr>
        <th>Last Name</th>
        <th>First Name</th>
        <th>Enrollment Date</th>
        <th>Academic Year</th>
        <th>&nbsp;</th>
    </tr>
</thead>

Finally, you will enable users to use a date picker control for the enrollment date; rather than requiring the user to type a properly formatted date. You will use the jQuery UI DatePicker widget. To add the date picker widget, you must edit the dynamic data template for DateTime properties. Open the DateTime_Edit.ascx file (located in the DynamicData -> FieldTemplates folder). Add the highlighted code to the file.

<%@ Control Language="C#" CodeBehind="DateTime_Edit.ascx.cs" Inherits="ContosoUniversity.DateTime_EditField" %>

<asp:TextBox ID="TextBox1" CssClass="DatePicker" runat="server" Text='<%# FieldValueEditString %>' Columns="20"></asp:TextBox>

<asp:RequiredFieldValidator runat="server" ID="RequiredFieldValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" Enabled="false" />
<asp:RegularExpressionValidator runat="server" ID="RegularExpressionValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" Enabled="false" />
<asp:DynamicValidator runat="server" ID="DynamicValidator1" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" />
<asp:CustomValidator runat="server" ID="DateValidator" CssClass="DDControl DDValidator" ControlToValidate="TextBox1" Display="Static" EnableClientScript="false" Enabled="false" OnServerValidate="DateValidator_ServerValidate" />

<script>
    if ($.isFunction($('.DatePicker').datepicker)) { 
        $('.DatePicker').datepicker();
    }
</script>

Your project already references the script files for jQuery and jQuery UI. The script element that you added checks whether the datepicker function exists, because this widget is not present in the script files for the mobile pages. Therefore, the date picker widget will not appear in the mobile pages.

To add a stylesheet for the jQuery datepicker widget, open Site.master and add the following stylesheet link to the head element:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

Run your application, and notice that you can now select the date.

with date picker

Known Issues

This preview release contains some issues that limit the use of ASP.NET Scaffolding. The known issues are:

  • Related model entities are not supported.
  • Visual Basic projects are not supported.
  • Web projects with Windows Authentication or No Authentication mode do not work. To work around:
    • Add Entity Framework as NuGet package.
  • The Empty Web Project template does not work. To work around:
    • Install NuGet packages for Entity Framework 6, jQuery (not mobile), FriendlyUrls, and aspnet.scriptmanager.jquery
    • Add an App_Data folder to your project.
    • Add a Global.asax file and add RouteConfig.RegisterRoutes(RouteTable.Routes); to Application_Start.
    • Add a master page to the project.
  • LightSwitch Server projects do not work. To work around:
    • Add a master page to the project.
    • Add Entity Framework 6 as a NuGet package.
  • Scaffolding 4.0 project does not work after being upgraded to 4.5. To work around:
    • Add Entity Framework 5 or Entity Framework 6 as a NuGet package.
Tom FitzMacken

By Tom FitzMacken, Tom FitzMacken is a Senior Programming Writer on the Web Platform & Tools Content team.

Table of Contents

ASP.NET 4.5

Getting Started with EF

Continuing with EF

ASP.NET AJAX

Ajax Control Toolkit

Data Access

Master Pages

Security

Deployment

Moving to ASP.NET 2.0

Tailspin Spyworks

Hands On Labs