Strongly Typed Data in ASP .NET Web Forms

In ASP .NET Web Forms you’ve previously had to use strings to specify which properties you’d like to output when databinding, which would probably end up looking something like the following.

In all likelihood it could probably look far less tidy if you’ve ever needed to do any formatting on values you’re about to output to the page. Not to mention the errors you’ll get if you ever rename a property on the model and forget about your web page (because Visual Studio will not warn you about these errors).

In .NET 4.5.1 a strongly typed data feature was introduced for ASP .NET Web Forms. This allows you to specify a type for your data on the binding control which lets you be able to specify properties to bind without the use of strings.

You can make use of this feature by writing code similar to the following.

As shown above you can now specify a type for the data you are about to bind using the ItemType property of the databinding control. This lets you then use the Item property in the templates to specify which properties of your model you would like to output (as well as allowing you access to any handy extension methods you may have for formatting output).

This on whole means you know if a change you have made has broken your model binding before runtime, which is definitely a great step forward for ASP .NET Web Forms development.

Using a RequiredFieldValidator on a DropDownList in ASP .NET

In most applications today drop-down lists default to a “Please select..” option with some form of validation to ensure the user makes their own selection.

Drop-down list validation example

In ASP .NET web forms this frequently results in a drop-down list being created using code similar to that displayed below.

We can add an ASP .NET RequiredFieldValidator and set its ControlToValidate property to the ID of the DropDownList control as shown below.

This code would result in the drop-down list always passing validation since theRequiredFieldValidator sees the default value of “-1” as a valid value.

To correct this we need to set the InitialValue¬†property of the RequiredFieldValidator to be the same as the initial value of the DropDownList (in this case “-1′) as shown below.

After this property has been set the DropDownList control will not pass validation until the user has selected a different option.