4.0 and Visual Studio 2010 Web Development Beta 1 Overview
4.0 and Visual Studio 2010 Web Development Beta 1 Overview
Contents
Core Services...........................................................................................2
Extensible Output Caching......................................................................................2
Auto-Start Web Applications...................................................................................4
Permanently Redirecting a Page..............................................................................6
The Incredible Shrinking Session State....................................................................6
Web Forms.............................................................................................23
Setting Meta Tags with the Page.Keywords and Page.Description Properties........23
Enabling View State for Individual Controls...........................................................25
Changes to Browser Capabilities...........................................................................26
Routing in ASP.NET 4.0..........................................................................................32
Setting Client IDs......................................................................................... ..........37
Persisting Row Selection in Data Controls.............................................................40
FormView Control Enhancements..........................................................................41
ListView Control Enhancements............................................................................42
Filtering Data with the QueryExtender Control......................................................42
Disclaimer..............................................................................................54
Core Services
ASP.NET 4 introduces a number of features that improve core ASP.NET services such
as output caching and session-state storage.
You create a custom output-cache provider as a class that derives from the new
System.Web.Caching.OutputCacheProvider type. You can then configure the
provider in the Web.config file by using the new providers subsection of the
outputCache element, as shown in the following example:
<caching>
<outputCache defaultProvider="AspNetInternalProvider">
<providers>
<add name="DiskCache"
type="Test.OutputCacheEx.DiskOutputCacheProvider, DiskCacheProvider"/>
</providers>
</outputCache>
</caching>
By default in ASP.NET 4.0, all HTTP responses, rendered pages, and controls use the
in-memory output cache, as shown in the previous example, where the
defaultProvider attribute is set to AspNetInternalProvider. You can change the default
output-cache provider used for a Web application by specifying a different provider
name for defaultProvider.
In addition, you can select different output-cache providers per control and per
request. The easiest way to choose a different output-cache provider for different
Web user controls is to do so declaratively by using the new providerName attribute
in a page or control directive, as shown in the following example:
Specifying a different output cache provider for an HTTP request requires a little
more work. Instead of declaratively specifying the provider, you instead override the
new GetOuputCacheProviderName method in the Global.asax file to
programmatically specify which provider to use for a specific request. The following
example shows how to do this.
if (context.Request.Path.EndsWith("Advanced.aspx"))
else
return base.GetOutputCacheProviderName(context);
With the addition of output-cache provider extensibility to ASP.NET 4.0, you can now
pursue more aggressive and more intelligent output-caching strategies for your Web
sites. For example, it is now possible to cache the "Top 10" pages of a site in
memory, while caching pages that get lower traffic on disk. Alternatively, you can
cache every vary-by combination for a rendered page, but use a distributed cache
so that the memory consumption is offloaded from front-end Web servers.
A new scalability feature named auto-start that directly addresses this scenario is
available when ASP.NET 4.0 runs on IIS 7.5 on Windows Server 2008 R2. The auto-
start feature provides a controlled approach for starting up an application pool,
initializing an ASP.NET application, and then accepting HTTP requests.
To use the auto-start feature, an IIS administrator sets an application pool in IIS 7.5
to be automatically started by using the following configuration in the
applicationHost.config file:
<applicationPools>
</applicationPools>
Because a single application pool can contain multiple applications, you specify
individual applications to be automatically started by using the following
configuration in the applicationHost.config file:
<sites>
<application path="/"
preloadEnabled="true"
</application>
</site>
</sites>
<preloadProviders>
<add name="PrewarmMyCache"
</preloadProviders>
You create a managed auto-start type with the necessary entry point by
implementing the IProcessHostPreloadClient interface, as shown in the following
example:
// Perform initialization.
After your initialization code runs in the Preload method and the method returns,
the ASP.NET application is ready to process requests.
ASP.NET 4.0 adds a new RedirectPermanent helper method that makes it easy to
issue HTTP 301 Moved Permanently responses, as in the following example:
RedirectPermanent("/newpath/foroldcontent.aspx");
Search engines and other user agents that recognize permanent redirects will store
the new URL that is associated with the content, which eliminates the unnecessary
round trip made by the browser for temporary redirects.
ASP.NET 4.0 introduces a new compression option for both kinds of out-of-process
session-state providers. When the compressionEnabled configuration option shown
in the following example is set to true, ASP.NET will compress (and decompress)
serialized session state by using the .NET Framework
System.IO.Compression.GZipStream class.
<sessionState
mode="SqlServer"
compressionEnabled="true"
/>
With the simple addition of the new attribute to the Web.config file, applications with
spare CPU cycles on Web servers can realize substantial reductions in the size of
serialized session-state data.
Simplicity — The template syntax must be very readable and must be optimized
for the most common scenario, namely one-way/one-time binding.
Components — When using the template syntax, the developer must be able to
instantiate client-side controls and behaviors that attach to HTML elements in
the page or within templates.
Template Example
The following example shows a typical client template that you can create using
ASP.NET 4.0.
sys:attach="dataview"
>
<li>
</li>
</ul>
The class attribute of the outer div element is set to sys-template, which is a
convention that is used in order to hide the initial template from the user. You
should define this class in your CSS style sheet as {display:none;}.
When the template is rendered, it has a data item as context. Fields or properties of
that data item can be included in the template markup by using {{ }} expressions —
for example, {{ Name }}, if the data item has a Name field. These expressions can be
placed anywhere in text content, or you can use them as the value of an attribute.
In addition to fields or properties, the expression blocks can also contain any
JavaScript expression that can be evaluated as a string.
You can set up DOM events by using the $addHandler method. The DOM on*
attributes of elements (for example, onclick=method) also work from within
templates.
The most convenient way to use client templates in ASP.NET 4.0 is through the
DataView control. The content of a DataView control is used as a template that
renders the data item that is provided to the control. If you set the DataView
<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
>
<li>
</li>
</ul>
</body>
You can also create a compiled template from code by using the Sys.UI.Template
class, as shown in the following example:
The constructor takes the parent element of the template as its argument. You can
then render a compiled template into the DOM by calling its instantiateIn method
and specifying an HTML container element and a data item as context. The
following example shows how to do this.
t.instantiateIn(
$get("targetContainer"),
Name: "Name",
Description: "Description"
In addition to providing access to fields and properties of the data item, the
template rendering engine also provides access to pre-defined "pseudo-columns"
such as $index and $dataItem. These pseudo-columns give you access to values
from the rendering engine at render time. You can use pseudo-columns the way you
use any JavaScript variable in the template instance. The first example applies a
different CSS class to the div element for alternating items that are rendered by the
dataView control. The second examples passes the pseudo-column $dataItem,
which represents the data for the current row, to a custom function named
nameConvert for processing.
<span>{{nameConvert($dataItem)}}</span>
You can add the new code:if, code:before, and code:after declarative attributes to
any DOM element within a template in order to render the element conditionally
(code:if) or to render arbitrary code before (code:before) or after (code:after) the
element. The following example shows how to use the code:If attribute to render an
hr element as a separator between items. The code:if attribute uses the value of the
$index pseudo-column to ensure that the hr element is rendered only between
items, and not before the first one or after the last one.
<li>
</li>
</ul>
The javascript:Sys namespace (typically mapped to the sys: prefix, as shown in the
example) is used for a number of system attributes. One of those system attributes
is sys:attach, which is used to specify a comma-separated list of controls or
behaviors to attach to the element, as shown in the following example:
<li>
</li>
</ul>
Declarative instantiation of controls will only work if the declarative markup is within
an element that has been configured, or activated, for this purpose. Templates
themselves are already activated, so declarative markup to instantiate and attach
controls works within a template. But to declaratively instantiate controls outside a
template, you must first configure the page to ensure that sys:attach markup is
within an activated element. You do this by including a sys:activate attribute on the
opening body tag, and setting its value to a comma-separated list of element IDs for
the elements that you want to allow declarative instantiation in. The following
example activates elements whose IDs are panel1 and panel2:
You can also activate every element in the document. However, doing so can cause
a small delay when the page is initialized, so the technique should be used with
caution on large pages. The following example shows how to activate the whole
document.
<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
>
<li>
</li>
</ul>
</body>
ClientElementsToActivate="panel1,panel2">
</Scripts>
</asp:ScriptManager>
In the example, the elements with ID panel1 and panel2 are activated. This example
also shows references to MicrosoftAjaxTemplates.js and MicrosoftAjaxAdoNet.js, which
contain most of the new ASP.NET AJAX features. For more information about these
scripts, see Refactoring the Microsoft AJAX Framework Libraries later in this
document.
You can use an alternative live-binding syntax in order to ensure that the target
value is automatically updated whenever the source value changes. This is shown in
the following example:
<h3>{binding Name}</h3>
With this binding syntax, if the Name field of the current data item is changed, the
rendered value will automatically be updated in response.
This example, where the binding is to a text node (the content of the h3 element),
illustrates one-way live binding. The source value (in this case, the data) binds one-
way to the target (in this case, an HTML text node), so when the source value
changes, the target is updated. But there is no binding from the target back to the
source.
Another form of live binding is two-way live binding, which is useful when a text box
is provided that enables users to modify the value of underlying data, as in the
following example:
In two-way live binding, the binding works in both directions. If the target value is
changed (in this case, the value in the UI), the source value is automatically
updated (in this case, the underlying data item). Similarly, if the source value is
changed (in this case, if the underlying data value is updated externally), the target
value (the value in the UI) is updated in response. As a result, target and source are
always in sync.
In the following example, if the user modifies the value in the text box, the value
that is rendered in the h3 element will automatically be updated to reflect the new
value that is provided by the user.
The live-binding syntax is similar to binding syntax in WPF (XAML). It can be used for
binding between UI and data, as in the above examples, as well as directly between
UI elements, between data and properties of declaratively attached controls and
components, and so on. The syntax also supports additional features, such as
providing functions for converting data values to rendered values, or converting
back from values entered in UI to an appropriately formatted data value. The
following example shows how to provide conversion functions:
However, in most cases this is not necessary, because the default binding behavior
is that text boxes and other input controls automatically use two-way binding, and
other bindings use one-way binding. In the previous example, this default behavior
is overridden so that if the data value changes, the value in the text box will
change, but if the user modifies the value in the UI, the underlying data value will
not be updated correspondingly.
The underlying technology that enables live bindings is the ASP.NET AJAX observer
pattern, which is used internally by the Binding class and is described in the next
section. For more information about binding, see The DataView Control later in this
document.
In the following example, the Sys.Observer class is used to add items to the
imagesArray array in a way that raises CollectionChanged notifications. As a result,
the DataView control will automatically update and display the inserted item after
the user has clicked the Insert button. This is possible because the DataView
control is bound to its source data (in this case, the imagesArray array that the data
property is set to) by using live binding.
<script type="text/javascript">
Sys.Observer.makeObservable(imageArray);
function onInsert() {
imagesArray.add(newImage);
</script>
<button onclick="onInsert()">Insert</button>
>
<li>
</li>
</ul>
Data can be provided to the DataView control in a number of ways. One way is by
setting the data property of the DataView control. The following example shows how
to set the DataView control’s data property through declarative binding:
>
<li>
</li>
</ul>
The following example shows how to set the DataView control’s data property
through code:
<script type="text/javascript">
function pageLoad() {
imagesService.GetImages(querySucceeded);
function querySucceeded(result) {
$find("imagesList").set_data(result);
</script>
<li>
</li>
</ul>
Another way to provide data is to specify a WCF or ASP.NET Web service directly in
the dataProvider property of the DataView control, as shown in the following
example:
dataview:dataprovider="../Services/imagesService.svc"
dataview:fetchOperation="GetImages"
>
<li>
</li>
</ul>
When the DataView control’s dataProvider property is set, the DataView control will
use the provider (in this case, the Web service) to fetch data by using the operation
specified in the fetchOperation property. For other examples in which the
dataProvider property is set to an instance of the DataContext class (used for read-
write scenarios) see The DataContext and AdoNetDataContext Classes later in this
document.
The DataView control provides a number of features that are not shown in the
previous examples, such as support for layout templates and external templates,
built-in selection support for use in master-detail scenarios, command bubbling, and
so on. The following example illustrates how to use some of these features to
configure linked master-detail views, using two DataView controls that are linked
through live binding.
<!--Master View-->
dataview:fetchOperation="GetImages"
dataview:selecteditemclass="myselected"
dataview:sys-key="master"
>
</ul>
<!--Detail View-->
<div class="sys-template"
sys:attach="dataview"
>
</div>
The Select command in the master view template ensures that when the user clicks
one of the items rendered by the master view, that item becomes the selected item.
As a result, the CSS class specified in the selectedItemClass property of the master
DataView control is applied to the markup for that item. In addition, the
corresponding data item becomes the value that is returned by the selectedData
property of the master DataView control.
The detail DataView control uses live binding so that its data item is dynamically set
to the current selectedData value of the master DataView control. In the example,
the detail view provides an edit template with two-way binding that lets users
modify the fields of the data item.
Typically, data is fetched from the server through JSON services such as a WCF AJAX-
enabled service or ADO.NET data services. The data is displayed to the user through
dynamic data-driven UI, using the DataView control. Declarative live-binding
markup in the template provides users with an edit UI, which enables them to
modify the data. The ASP.NET AJAX DataContext class tracks all changes to the data
automatically. All changes can then be sent at once to the server by calling the
SaveChanges method of the DataContext class. A single DataContext instance can
manage change tracking for data returned by different operations on the server,
even if the operations return different types of objects.
<script type="text/javascript">
dataContext.set_serviceUri("../Services/imagesService.svc");
dataContext.set_saveOperation("SaveImages");
dataContext.initialize();
</script>
dataview:query="GetImages"
>
<li>
</li>
If you are using an ADO.NET data service, you should use the AdoNetDataContext
class instead of the more general-purpose DataContext class. (AdoNetDataContext
derives from DataContext.) The AdoNetDataContext class provides additional
support for features that are specific to ADO.NET, such as identity management,
links and associations between entity sets that are returned in different fetch
operations, hierarchical data, and optimistic concurrency.
<Scripts>
</Scripts>
</asp:ScriptManager>
ASP.NET 4.0 also introduces the ability to use only parts of the ASP.NET AJAX
framework for efficiency, as well as the ability to use the ScriptManager control
without using the ASP.NET AJAX framework at all. The ScriptManager control
provides services such as centralized management of references, support for debug
and release modes, support for localization, and script combining. These services
can be useful to all client-script developers, even those who use JavaScript libraries
other than Microsoft AJAX, such as jQuery. Until now, the ScriptManager control
included the Microsoft ASP.NET AJAX library automatically, without providing a
simple way to opt out of it. As a result, when developers used the ScriptManager
control in their pages, the effect was to include the whole Microsoft ASP.NET AJAX
library in their applications.
In ASP.NET 4.0, the default behavior for the ScriptManager control is to include the
complete ASP.NET AJAX library. However, the ScriptManager control supports a new
MicrosoftAjaxMode property that lets you choose a subset of the framework by
Enabled — All Microsoft AJAX scripts are included (legacy behavior). This is the
default value of the property.
Explicit — Each split script file must be added explicitly; it is up to you to make
sure that you include all scripts that have dependencies on one another.
Disabled — All Microsoft ASP.NET AJAX script features are disabled and the
ScriptManager control does not reference any scripts automatically.
When you use Explicit mode, the scripts that are available are as follows:
• MicrosoftAjaxCore.js
• MicrosoftAjaxComponentModel.js
• MicrosoftAjaxSerialization.js
• MicrosoftAjaxGlobalization.js
• MicrosoftAjaxHistory.js
• MicrosoftAjaxNetwork.js
• MicrosoftAjaxWebServices.js
• MicrosoftAjaxApplicationServices.js
The following chart shows the dependencies between split scripts. The violet boxes
that are labeled Templates (AdoNetDataContext) and Templates
(DataContext) indicate that only these classes in MicrosoftAjaxTemplates.js have
the indicated dependency. Thus, MicrosoftAjaxTemplates.js does not require
MicrosoftAjaxWebServices.js unless you use the DataContext class, and it does not
require MicrosoftAjaxAdoNet.js unless you use the AdoNetDataContext class.
As an example, to use the ASP.NET AJAX browser history feature with no partial
rendering and with MicrosoftAjaxMode set to Explicit, the ScriptManager control
must be configured as in the following example:
<asp:ScriptManager ID="ScriptManager1"
EnablePartialRendering="false"
MicrosoftAjaxMode="Explicit"
EnableHistory="true"
runat="server">
<CompositeScript>
<Scripts>
</Scripts>
</CompositeScript>
</asp:ScriptManager>
Note that split script files should be used only by developers who are concerned
about optimizing for very high performance. When split script files are used, they
should be used together with script combining to minimize the numbers of requests
that are required in order to download the scripts.
Web Forms
Web Forms has been a core feature in ASP.NET since the release of ASP.NET 1.0.
Many enhancements have been in this area for ASP.NET 4.0, including the following:
More control over rendered HTML in the FormView and ListView controls.
<title>Untitled Page</title>
<meta name="keywords" content="These, are, my, keywords' />
<meta name="description" content="This is the description of my page" />
</head>
These two properties work the same way that the page’s Title property does. They
follow these rules:
If there are no meta tags in the head element that match the property names (that
is, name="keywords" for Page.Keywords and name="description" for Page.Description,
meaning that these properties have not been set), the meta tags will be added to
the page when it is rendered.
If there are already meta tags with these names, these properties act as get and set
methods for the contents of the existing tags.
You can set these properties at run time, which lets you get the content from a
database or other source, and which lets you set the tags dynamically to describe
what a particular page is for.
You can also set the Keywords and Description properties in the @ Page directive at
the top of the Web Forms page markup, as in the following example:
CodeFile="Default.aspx.cs"
Inherits="_Default"
This will override the meta tag contents (if any) already declared in the page.
Only the contents of the description meta tag is used for improving search listing
previews in Google. (For details, see Improve snippets with a meta description
makeover on the Google Webmaster Central blog.) Google and Windows Live Search
do not use the contents of the keywords for anything, but other search engines
might. For more information, see Meta Keywords Advice on the Search Engine Guide
Web site.
These new properties are a simple feature, but they save you from the requirement
to add these manually or from writing your own code to create the meta tags.
The ViewStateMode property has three possible values: Enabled, Disabled, and
Inherit. The function of the property is probably clear from the names of these
settings. Enabled enables view state for that control (or for any child controls that
are set to Inherit or that have nothing set). Disabled disables view state, and Inherit
specifies that the control gets its ViewStateMode setting from the parent control.
The following simple example shows how the ViewStateMode property works. The
markup for the controls in the following page includes a ViewStateMode value:
<script runat=”server”>
if (!IsPostBack) {
base.OnLoad(e);
</script>
</asp:PlaceHolder>
</asp:PlaceHolder>
<hr />
The effect of these settings is that when the page loads the first time, the following
output is displayed in the browser:
Disabled: [DynamicValue]
Enabled: [DynamicValue]
Disabled: [DeclaredValue]
Enabled: [DynamicValue]
As you probably expect, label1 (whose ViewStateMode value is set to Disabled) has
not preserved the value that it was set to in code. However, label2 (whose
ViewStateMode value is set to Enabled) has preserved its state.
You can also set ViewStateMode in the @ Page directive, as in the following
example:
CodeBehind="Default.aspx.cs"
Inherits="WebApplication1._Default"
ViewStateMode="Disabled" %>
The Page class is just another control; it acts as the parent control for all the other
controls in the page. This means that no control will save view state unless you set
ViewStateMode to Enabled for that control or a control further up its control
hierarchy, which includes the page. A good use for this feature is with
ContentPlaceHolder controls in master pages, where you can set ViewStateMode to
Disabled for the master page and then enable it individually for ContentPlaceHolder
controls that in turn contain controls that require view state.
\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\Browsers
After you define the browser capability, you run the following command from the
Visual Studio Command Prompt in order to rebuild the browser capabilities
assembly and add it to the GAC:
aspnet_regbrowsers.exe –I c
These approaches require you to change XML files, and for machine-level changes,
you must restart the application after you run the aspnet_regbrowsers.exe process.
There are two main approaches for using the new ASP.NET 4.0 browser capabilities
provider feature: extending the ASP.NET browser capabilities definition functionality,
or totally replacing it. The following sections describe first how to replace the
functionality, and then how to extend it.
values[String.Empty] = request.UserAgent;
values["browser"] = "MyCustomBrowser";
browserCaps.Capabilities = values;
return browserCaps;
In order to use a provider with an application, you must add the provider attribute
to the browserCaps section in the Web.config or Machine.config files. (You can also
define the provider attributes in a location element for specific directories in
application, such as in a folder for a specific mobile device.) The following example
shows how to set the provider attribute in a configuration file:
<system.web>
</system.web>
Another way to register the new browser capability definition is to use code, as
shown in the following example:
HttpCapabilitiesBase.BrowserCapabilitiesProvider =
new ClassLibrary2.CustomProvider();
// ...
This code must run in the Application_Start event of the Global.asax file. Any change
to the BrowserCapabilitiesProvider class must occur before any code in the
application executes, in order to make sure that the cache remains in a valid state
for the resolved HttpCapabilitiesBase object.
The preceding example has one problem, which is that the code would run each
time the custom provider is invoked in order to get the HttpBrowserCapabilities
object. This can happen multiple times during each request. In the example, the
code for the provider does not do much. However, if the code in your custom
provider performs significant work in order to get the HttpBrowserCapabilities
object, this can result in huge overhead. To prevent this from happening, you can
cache the HttpBrowserCapabilities object. Follow these steps:
2. Create a class that derives from HttpCapabilitiesProvider, like the one in the
following example:
GetBrowserCapabilities(HttpRequest request)
HttpBrowserCapabilities browserCaps =
HttpContext.Current.Cache[cacheKey] as
HttpBrowserCapabilities;
if (browserCaps == null)
HttpBrowserCapabilities();
values[String.Empty] = request.UserAgent;
values["browser"] = "MyCustomBrowser";
browserCaps.Capabilities = values;
HttpContext.Current.Cache.Insert(cacheKey,
TimeSpan.FromSeconds(cacheTime));
return browserCaps;
Register the provider with the application as described in the preceding procedure.
3. Create a class that derives from HttpCapabilitiesEvaluator and that overrides the
GetBrowserCapabilities method, like the one in the following example:
GetBrowserCapabilities(HttpRequest request)
HttpBrowserCapabilities browserCaps =
base.GetHttpBrowserCapabilities(request);
if (browserCaps.Browser == "Unknown")
browserCaps = MyBrowserCapabilitiesEvaulator(request);
return browserCaps;
This code first uses the ASP.NET browser capabilities functionality to try to
identify the browser. However, if no browser is identified based on the
information defined in the request (that is, if the Browser property of the
HttpBrowserCapabilities object is the string “Unknown”), the code calls the
custom provider (MyBrowserCapabilitiesEvaluator) to identify the browser.
Register the provider with the application as described in the previous example.
4. Create a class that derives from HttpCapabilitiesEvaluator and that overrides the
GetBrowserCapabilities method, like the one in the following example:
GetBrowserCapabilities(HttpRequest request)
base.GetHttpBrowserCapabilities(request);
browserCaps.Frames = true;
browserCaps.Capabilities["MultiTouch"] = "true";
return browserCaps;
HttpBrowserCapabilities browserCaps =
base.GetHttpBrowserCapabilities(request);
The code can then add or modify a capability for this browser. There are two
ways to specify a new browser capability:
Register the provider with the application as described in the earlier procedure.
http://website/products.aspx?categoryid=12
http://website/products/software
It has been possible to use routing by using the routing feature that shipped with
ASP.NET 3.5 SP1. (For an example of how this is done, see the entry Using Routing
With WebForms on Phil Haack's blog.) However, ASP.NET 4.0 includes some features
that make it easier to use routing, including the following:
The WebFormRouteHandler class, which is a simple HTTP handler that you use
when you define routes. Its function is to pass data to the page that the request
is routed to.
The next sections describe how these new types and members fit together.
Examine the following code, which defines a Web Forms route by using the new
WebFormRouteHandler class:
new WebFormRouteHandler("~/search.aspx")));
As you can see, the code maps the route to a physical page (in the first route, to
~/search.aspx). The first route definition also specifies that the parameter named
searchterm should be extracted from the URL and passed to the page.
<configuration>
<location path="search.aspx">
<system.web>
<authorization>
<allow roles="admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
<location path="search">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
In the example configuration, access is denied to the physical page search.aspx for
all users except those who are in the admin role. When the checkPhysicalUrlAccess
parameter is set to true (which is its default value), only admin users are allowed to
access the URL /search/{searchterm}, because the physical page search.aspx is
restricted to users in that role.
In the code of the Web Forms physical page, how do you access the information that
the routing system has extracted from the URL? (Or access any other information
that another object might have added to the RouteData object.) As noted earlier,
ASP.NET 4.0 provides two new properties for this purpose,
HttpRequest.RequestContext and Page.RouteData. (Page.RouteData just wraps
HttpRequest.RequestContext.RouteData.)
label1.Text = searchterm;
The code simply extracts the value that was passed for the searchterm parameter, as
defined in the example route earlier. Consider the following request URL:
http://localhost/search/scott/
When this request is made, the word "scott" would be rendered in the search.aspx
page.
You can use the method described here to get route data in code. You can also use
expressions in markup that give you access to the same information.
Expression builders have been described as a "hidden gem of ASP.NET" (see the
entry Express Yourself With Custom Expression Builders on Phil Haack's blog). It is
ASP.NET 4.0 includes two new expression builders for Web Forms routing. The
following example shows how to use them.
In the example, the RouteUrl expression builder is used to define a URL that is
based on a route parameter. This saves you from having to hard-code the complete
URL into the markup, and lets you change the URL structure later, if necessary,
without requiring any change to this link.
Based on the route defined earlier, this markup generates the following URL:
http://localhost/search/scott
Note that ASP.NET automatically works out the correct route (that is, it generates
the correct URL) based on the input parameters. You can also include a route name
in the expression, which lets you specify a route to use.
The following example shows how to use the RouteValue expression builder.
When the page that contains this control runs, the value "scott" is displayed in the
label.
The RouteValue expression builder makes it very simple to use route data in
markup, and it avoids having to work with the more complex Page.RouteData["x"]
syntax in markup.
The RouteParameter class lets you specify route data as a parameter value for
queries in a data source control. It works much like FormParameter, as shown in the
following example:
CompanyName=@companyname"
<selectparameters>
</asp:sqldatasource>
In this case, the value of the route parameter searchterm will be used for the
@companyname parameter in the Select statement.
The id attribute for Web server controls is generated based on the ClientId property
of the control. The algorithm up to now for generating the id attribute from the
ClientId property has been to concatenate the naming container (if any) with the ID,
and in the case of repeated controls (as in data controls), to add a prefix and a
sequential number. While this has always guaranteed that the IDs of controls in the
page are unique, the algorithm has resulted in control IDs that were not predictable,
and were therefore difficult to reference in client script.
The new ClientIdMode property lets you specify more precisely how the client ID is
generated for controls. You can set the ClientIdMode property for any control,
including for the page. Possible settings are the following:
Legacy – This is equivalent to the ClientID property behavior for earlier versions
of ASP.NET. This is also the default if no ClientIdMode property is set in the
current control’s hierarchy.
Static – This lets you specify an ID to be used as-is, no matter what naming
container the control is in. (This is sometimes referred to as the "you set it, you
get it" option.) The Static option gives you the most control over the ID, but is
the least safe, in that ASP.NET does not prevent you from generating duplicate or
invalid IDs.
Predictable – This option is primarily for use in data controls that use repeating
templates. It uses ID attributes of the parent control's naming containers, but
generated IDs do not have names that contain strings like "ctlxxx". Only a user-
defined ID will be included in the resulting control ID. This setting works in
conjunction with the RowClientIdSuffix property of the parent control to allow
you to define values that create unique IDs for each instance of the control. A
typical example is to use the primary key of a data record as part of the client ID.
Inherit – This setting is the default behavior for controls; it specifies that a
control's ID generation is the same as its parent. Explicitly setting ClientIdMode
to Inherit specifies that this and any child controls whose ClientIdMode property
is either not set or is set to Inherit will take the ClientIdMode value of any parent
You can set the ClientIdMode property at the page level. This defines the default
ClientIdMode value for all controls in the current page. You set the page-level value
in the @ Page directive, as shown in the following example:
CodeFile="Default.aspx.cs"
Inherits="_Default"
ClientIdMode="Predictable" %>
You can also set the ClientIdMode value in the configuration file, either at the
machine level or at the application level. This defines the default ClientIdMode
setting for all controls in all pages in the application. If you set the value at the
machine level, it defines the default ClientIdMode setting for all Web sites on that
computer. The following example shows the ClientIdMode setting in the
configuration file:
<system.web>
<pages clientIdMode="Predictable"></pages>
</system.web>
As noted earlier, the value of the ClientId property is derived from the naming
container for a control’s parent. In some scenarios, such as when you are using
master pages, controls can end up with IDs like those in the following rendered
HTML:
<div id="ctl00_ContentPlaceHolder1_ParentPanel">
<div id="ctl00_ContentPlaceHolder1_ParentPanel_NamingPanel1">
<input name="ctl00$ContentPlaceHolder1$ParentPanel$NamingPanel1$TextBox1"
type="text" value="Hello!"
id="ctl00_ContentPlaceHolder1_ParentPanel_NamingPanel1_TextBox1" />
</div>
Even though the input element (from a TextBox control) shown in the markup is only
two naming containers deep in the page (the nested ContentPlaceholder controls),
because of the way master pages are processed, the end result is a control ID like
the following:
ctl00_ContentPlaceHolder1_ParentPanel_NamingPanel1_TextBox1
</tc:NamingPanel>
</tc:NamingPanel>
In this sample, the ClientIdMode property is set to Static for the outermost
NamingPanel element, and set to Predictable for the inner NamingControl element.
These settings result in the following markup (the rest of the page and the master
page is assumed to be the same as in the previous example):
<div id="ParentPanel">
<div id="ParentPanel_NamingPanel1">
<input name="ctl00$ContentPlaceHolder1$ParentPanel$NamingPanel1$TextBox1"
</div>
This has the effect of resetting the naming hierarchy for any controls inside the
outermost NamingPanel element, and of eliminating the ContentPlaceHolder and
MasterPage IDs from the generated ID. (Note that the name attribute of rendered
elements is unaffected, so that the normal ASP.NET functionality is retained for
events, view state, and so on.) A nice side effect of resetting the naming hierarchy
is that even if you move the markup for the NamingPanel elements to a different
ContentPlaceholder control, the rendered client IDs remain the same.
Note It is up to you to make sure that the rendered control IDs are unique. If
they are not, it can break any functionality that requires unique IDs for individual
HTML elements, such as the client document.getElementById function.
The ClientID values that are generated for controls in a data-bound list control can
be long and are not really predictable. The ClientIdMode functionality can help you
have more control over how these IDs are generated.
onselectedindexchanged="ListView1_SelectedIndexChanged"
ClientIdMode="Predictable"
RowClientIdSuffix="ProductID">
</asp:ListView>
In the previous example, the ClientIdMode and RowClientIdSuffix properties are set
in markup. The RowClientIdSuffix property can be used only in data-bound controls,
and its behavior differs depending on which control you are using. The differences
are these:
GridView control — You can specify the name of one or more columns in the data
source, which are combined at run time to create the client IDs. For example, if
you set RowClientIdSuffix to “ProductName, ProductId”, control IDs for rendered
elements will have a format like the following:
rootPanel_GridView1_ProductNameLabel_Chai_1
ListView control — You can specify a single column in the data source that is
appended to the client ID. For example, if you set RowClientIdSuffix to
“ProductName”, the rendered control IDs will have a format like the following:
rootPanel_ListView1_ProductNameLabel_1
In this case the trailing 1 is derived from the product ID of the current data item.
Repeater control— This control does not support the RowClientIdSuffix property.
In a Repeater control, the index of the current row is used. When you use
ClientIdMode="Predictable" with a Repeater control, client IDs are generated that
have the following format:
Repeater1_ProductNameLabel_0
The FormView and DetailsView controls do not display multiple rows, so they do not
support the RowClientIdSuffix property.
Persisted selection is a new feature that was initially supported only in Dynamic
Data projects in the .NET Framework 3.5 SP1. When this feature is enabled, the
</asp:GridView>
<ItemTemplate>
Content!
</ItemTemplate>
</asp:FormView>
This markup renders the following output to the page; notice that the FormView
control renders an HTML table:
<tr>
<td colspan="2">
Content!
</td>
</tr>
</table>
A new RenderTable property is now available that lets you specify whether the
FormView control renders using a table. The following example shows how to set
the property.
Content!
This enhancement can make it easier to style the content of the control with CSS,
because no unexpected tags are rendered by the control.
<LayoutTemplate>
</LayoutTemplate>
<ItemTemplate>
<% Eval("LastName")%>
</ItemTemplate>
</asp:ListView>
In ASP.NET 4.0, the ListView control does not require a layout template. The markup
shown in the previous example can be replaced with the following markup:
<ItemTemplate>
<% Eval("LastName")%>
</ItemTemplate>
</asp:ListView>
To make filtering easier, a new QueryExtender control has been added in ASP.NET
4.0. This control can be added to EntityDataSource or LinqDataSource controls in
order to filter the data returned by these controls. Because the QueryExtender
control relies on LINQ, the filter is applied on the database server before the data is
sent to the page, which results in very efficient operations.
Search
For the search option, the QueryExtender control uses provided text to find records
in specified fields. In the following example, the control uses the text that is entered
in the TextBoxSearch control and searches for its contents in the ProductName and
Supplier.CompanyName columns in the data returned from the LinqDataSource control.
</asp:LinqDataSource>
SearchType="StartsWith">
</asp:SearchExpression>
</asp:QueryExtender>
Range
The range option is similar to the search option, but specifies a pair of values to
define the range. In the following example, the QueryExtender control searches the
UnitPrice column in the data returned from the LinqDataSource control. The range is
read from the TextBoxFrom and TextBoxTo controls on the page.
</asp:LinqDataSource>
MaxType="Inclusive">
</asp:RangeExpression>
</asp:QueryExtender>
PropertyExpression
The property expression option lets you define a comparison to a property value. If
the expression evaluates to true, the data that is being examined is returned. In the
following example, the QueryExtender control filters data by comparing the data in
the Discontinued column to the value from the CheckBoxDiscontinued control on the
page.
</asp:LinqDataSource>
<asp:PropertyExpression>
</asp:PropertyExpression>
</asp:QueryExtender>
CustomExpression
Finally, you can specify a custom expression to use with the QueryExtender control.
This option lets you call a function in the page that defines custom filter logic. The
following example shows how to declaratively specify a custom expression in the
QueryExtender control.
</asp:LinqDataSource>
</asp:QueryExtender>
The following example shows the custom function that is invoked by the
QueryExtender control. In this case, instead of using a database query that includes
a Where clause, the code uses a LINQ query to filter the data.
select p;
These examples show only one expression being used in the QueryExtender control
at a time. However, you can include multiple expressions inside the QueryExtender
control.
Dynamic Data
Dynamic Data was introduced in the .NET Framework 3.5 SP1 release in mid-2008.
This feature provides many enhancements for creating data-driven applications,
including the following:
The ability to easily change the markup that is generated for fields in the
GridView and DetailsView controls by using field templates that are part of your
Dynamic Data project.
Note For more information, see the Dynamic Data documentation in the
MSDN Library.
For ASP.NET 4.0, Dynamic Data has been enhanced to give developers even more
power for quickly building data-driven Web sites.
AutoLoadForeignKeys="true">
<DataControls>
</DataControls>
</asp:DynamicDataManager>
</asp:GridView>
This markup enables Dynamic Data behavior for the GridView1 control that is
referenced in the DataControls section of the DynamicDataManager control.
Entity Templates
Entity templates offer a new way to customize the layout of data without requiring
you to create a custom page. Page templates use the FormView control (instead of
the DetailsView control, as used in page templates in earlier versions of Dynamic
Data) and the DynamicEntity control to render Entity templates. This gives you
more control over the markup that is rendered by Dynamic Data.
The following list shows the new project directory layout that contains entity
templates:
\DynamicData\EntityTemplates
\DynamicData\EntityTemplates\Default.ascx
\DynamicData\EntityTemplates\Default_Edit.ascx
\DynamicData\EntityTemplates\Default_Insert.ascx
The EntityTemplate directory contains templates for how to display data model
objects. By default, objects are rendered by using the Default.ascx template, which
provides markup that looks just like the markup created by the DetailsView control
used by Dynamic Data in ASP.NET 3.5 SP1. The following example shows the
markup for the Default.ascx control:
<ItemTemplate>
<tr
<td>
</td>
<td>
</td>
</tr>
</asp:EntityTemplate>
The default templates can be edited to change the look and feel for the entire site.
There are templates for display, edit, and insert operations. New templates can be
added based on the name of the data object in order to change the look and feel of
just one type of object. For example, you can add the following template:
\DynamicData\EntityTemplates\Products.aspx
<tr>
<td>Name</td>
<td>Category</td>
</tr>
The new entity templates are displayed on a page by using the new DynamicEntity
control. At run time, this control is replaced with the contents of the entity template.
The following markup shows the FormView control in the Detail.aspx page template
that uses the entity template. Notice the DynamicEntity element in the markup.
DataSourceID="DetailsDataSource"
OnItemDeleted="FormView1_ItemDeleted">
<ItemTemplate>
<tr class="td">
<td colspan="2">
CommandName="Delete"
CausesValidation="false"
Text="Delete" />
</td>
</tr>
</table>
</ItemTemplate>
</asp:FormView>
[DataType(DataType.EmailAddress)]
[DataType(DataType.Url)]
Action="List" TableName="Products">
</asp:DynamicHyperLink>
The EnumDataTypeAttribute class has been added to let you map fields to
enumerations. When you apply this attribute to a field, you specify an enumeration
type. Dynamic Data uses the new Enumeration.ascx field template to create UI for
displaying and editing enumeration values. The template maps the values from the
database to the names in the enumeration.
An additional enhancement is that filtering support has been rewritten to use the
new QueryExtender feature of Web Forms. This lets you create filters without
requiring knowledge of the data source control that the filters will be used with.
Along with these extensions, filters have also been turned into template controls,
which allows you to add new ones. Finally, the DisplayAttribute class mentioned
earlier allows the default filter to be overridden, in the same way that UIHint allows
the default field template for a column to be overridden.
Visual Studio 2010 includes over 200 snippets that help you auto-complete common
ASP.NET and HTML tags, including required attributes (such as runat="server") and
common attributes specific to a tag (such as ID, DataSourceID, ControlToValidate,
and Text).
You can download additional snippets, or you can write your own snippets that
encapsulate the blocks of markup that you or your team use for common tasks.
Deploying to a shared hosting site requires technologies such as FTP, which can
be slow. In addition, you must manually perform tasks such as running SQL
scripts to configure a database and you must change IIS settings, such as
configuring a virtual directory folder as an application.
Visual Studio 2010 includes technologies that address these issues and that let you
seamlessly deploy Web applications. One of these technologies is the IIS Web
Deployment Tool (MsDeploy.exe).
Note The IIS Web Deployment Tool is a free download that is currently in Beta
test. For download information, see the entry The Web Deployment Tool Beta 2 is
now available! on the Microsoft Web Deployment Tool team blog.
Web deployment features in Visual Studio 2010 include the following major areas:
Web packaging
Database deployment
One-Click publishing
Web Packaging
Visual Studio 2010 uses the MSDeploy tool to create a compressed (.zip) file for your
application, which is referred to as a Web package. The package file contains
metadata about your application plus the following content:
The actual Web content, which includes Web pages, user controls, static content
(images and HTML files), and so on.
A Web package can be copied to any server and then installed manually by using IIS
Manager. Alternatively, for automated deployment, the package can be installed by
using command-line commands or by using deployment APIs.
Web.Config Transformation
For Web application deployment, Visual Studio 2010 introduces XML Document
Transform (XDT), which is a feature that lets you transform a Web.config file from
development settings to production settings. Transformation settings are specified
in transform files named web.debug.config, web.release.config, and so on. (The names
of these files match MSBuild configurations.) A transform file includes just the
changes that you need to make to a deployed Web.config file. You specify the
changes by using simple syntax.
<connectionStrings xdt:Transform="Replace">
</connectionStrings>
Database Deployment
A Visual Studio 2010 deployment package can include dependencies on SQL Server
databases. As part of the package definition, you provide the connection string for
your source database. When you create the Web package, Visual Studio 2010
creates SQL scripts for the database schema and optionally for the data, and then
adds these to the package. You can also provide custom SQL scripts and specify the
sequence in which they should run on the server. At deployment time, you provide a
connection string that is appropriate for the target server; the deployment process
then uses this connection string to run the scripts that create the database schema
and add the data.
Resources
The following Web sites provide additional information about ASP.NET 4.0 and Visual
Studio 2010.
The information contained in this document represents the current view of Microsoft
Corporation on the issues discussed as of the date of publication. Because Microsoft
must respond to changing market conditions, it should not be interpreted to be a
commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy
of any information presented after the date of publication.
Complying with all applicable copyright laws is the responsibility of the user.
Without limiting the rights under copyright, no part of this document may be
reproduced, stored in or introduced into a retrieval system, or transmitted in any
form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft
Corporation.
The names of actual companies and products mentioned herein may be the
trademarks of their respective owners.