Setting Client IDs in routing function of asp.net 4.0
The new ClientIDMode property addresses a long-standing issue in ASP.NET, namely how controls create the id attribute for elements that they render. Knowing the id attribute for rendered elements is important if your application includes client script that references these elements.
The id attribute in HTML that is rendered 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:
· AutoID – This is equivalent to the algorithm for generating ClientID property values that was used in earlier versions of ASP.NET.
· Static – This specifies that the ClientID value will be the same as the ID without concatenating the IDs of parent naming containers. This can be useful in Web user controls. Because a Web user control can be located on different pages and in different container controls, it can be difficult to write client script for controls that use the AutoID algorithm because you cannot predict what the ID values will be.
· Predictable – This option is primarily for use in data controls that use repeating templates. It concatenates the ID properties of the control's naming containers, but generated ClientID values do not contain strings like "ctlxxx". This setting works in conjunction with the ClientIDRowSuffix property of the control. You set the ClientIDRowSuffix property to the name of a data field, and the value of that field is used as the suffix for the generated ClientID value. Typically you would use the primary key of a data record as the ClientIDRowSuffix value.
· Inherit – This setting is the default behavior for controls; it specifies that a control's ID generation is the same as its parent.
You can set the ClientIDMode property at the page level. This defines the default ClientIDMode value for all controls in the current page.
The default ClientIDMode value at the page level is AutoID, and the default ClientIDMode value at the control level is Inherit. As a result, if you do not set this property anywhere in your code all controls will default to the AutoID algorithm.
You set the page-level value in the @ Page directive, as shown in the following example:
<%@ Page Language="C#" AutoEventWireup="true"
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
This is a long ID. It is guaranteed to be unique in the page, but is unnecessarily long for most purposes. Imagine that you want to reduce the length of the rendered ID, and to have more say in how the ID is generated (for example, you want to eliminate “ctlxxx” prefixes). The easiest way to achieve this is by setting the ClientIDMode property as shown in the following example:
<tc:NamingPanel runat="server" ID="ParentPanel" ClientIDMode="Static">
<tc:NamingPanel runat="server" ID="NamingPanel1" ClientIDMode="Predictable">
<asp:TextBox ID="TextBox1" runat="server" Text="Hello!"></asp:TextBox>
</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"
type="text" value="Hello!" id="ParentPanel_NamingPanel1_TextBox1" />
</div>
The Static setting 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.
Posted in: asp.net | Tags: asp.net 4.0 clientid individual id getelementbyid masterpage contentplaceholder clientidrowsuffixNew Features in ASP.NET AJAX 4
New Features in ASP.NET AJAX 4
Note The documentation in this section concerns ASP.NET 4 AJAX Preview 4. A more recent preview release might be available at the URL above. If so, it will include updated documentation.
The new functionality in ASP.NET AJAX enables new client data scenarios for page and component developers that enable JSON data from the server to be rendered as HTML in a highly manageable and efficient way. To enable these scenarios, ASP.NET AJAX includes the following major features:
· Client-side template rendering.
· Declarative instantiation of client-side behaviors and controls.
· Live data binding.
· Use of the observer pattern with JavaScript types.
· An AdoNetServiceProxy class for client-side interaction with ADO.NET Data Services.
· A client-side DataView control for data-bound UI in the browser.
· DataContext and AdoNetDataContext classes for interaction with Web services.
· Refactored ASP.NET AJAX framework libraries.
· Support for the DOM Ready event.
· Using JSONP to retrieve cross-domain data.
Client Template Rendering
In client-based development, templates are the most manageable way of creating UI from data. ASP.NET AJAX 4 includes a new template engine for client development that meets the following requirements:
· Performance — The engine must be able to render a typical number of items using a reasonably complex template before users perceive an interruption in their interaction with the application.
· Simplicity — The template syntax must be very readable and must be optimized for the most common scenario, namely one-way/one-time binding.
· Expression language — Templates must support an expression language to go beyond the simplest cases. The expression language should use familiar syntax, ideally JavaScript syntax.
· Interspersed code and markup — It must be possible to perform conditional rendering or to loop over markup by using code that surrounds HTML.
· 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 AJAX 4.
<ul id="myTemplate" class="sys-template"
sys:attach="dataview"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</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.
Instantiating a Template by Using the DataView Control
The most convenient way to use client templates in ASP.NET AJAX 4 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 control's data property to an array, the template is rendered once for each item in the array. The DataView control binds to live data, meaning that the control is automatically updated when the data changes, without the need to rebind. This provides a dynamic data-driven UI in the browser. The following example shows the declarative markup for a DataView control that binds to an array named imagesArray.
<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
<ul sys:attach="dataview" class="sys-template"
dataview:data="{{ imagesArray }}"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</li>
</ul>
</body>
Instantiating a Template by Using Code
You can also create a compiled template from code by using the Sys.UI.Template class, as shown in the following example:
var t = new Sys.UI.Template($get("myTemplate"));
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"
}
);
Using Pseudo-Columns in a Template
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.
<div class:alternateitem="{{$index%2 == 1}}">
<span>{{nameConvert($dataItem)}}</span>
Incorporating Code into a Template by Using the code:if, code:before, and code:after Attributes
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.
<ul id="myTemplate" class="sys-template">
<li>
<hr code:if="$index!==0" />
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</li>
</ul>
Posted in: asp.net | Tags: asp.net asp.net 4.0 performance feature asp.net ajax ajax dataview adonetdatacontext datacontext rendering simplicity template exampleNew Features in ASP.NET AJAX 4, Part 2
Instantiating Behaviors and Controls Declaratively
ASP.NET AJAX 4 introduces a way to declaratively instantiate client-side controls and behaviors and attach them to HTML elements. The declarative markup is achieved without adding any new HTML elements, simply by including additional namespaced attributes which are XHTML compliant.
Declarative Instantiation Within a Template
Suppose that you want to add a Contoso.DatePicker control to a div element. In ASP.NET AJAX 4, you can start by declaring a namespace prefix in the opening <body> tag (or in a template's parent tag), similar to the way the @ Register directive works in server-based files. The following example shows a namespace declaration.
<body xmlns:sys="javascript:Sys" xmlns:datepicker="javascript:Contoso.DatePicker">
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:
<ul id="myTemplate" class="sys-template">
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
<div sys:attach="datepicker" datepicker:date="{{ CreatedDate }}"></div>
</li>
</ul>
The example shows how to instantiate a Contoso.DatePicker control that is attached to a div element and how to set the control's date property to the value of the CreatedDate field of the current data item.
Declarative Instantiation Outside a Template
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:
<body xmlns:sys="javascript:Sys" sys:activate="panel1,panel2">
This causes the ASP.NET AJAX framework to scan the children of those elements for any sys:attach attributes, and to instantiate the corresponding controls.
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" sys:activate="*">
A DataView control is typically attached to an element that is not already within a template. This is a common reason to use sys:activate, as in the following complete example:
<body xmlns:sys="javascript:Sys"
xmlns:dataview="javascript:Sys.UI.DataView"
sys:activate="*">
<ul sys:attach="dataview" class="sys-template"
dataview:data="{{ imagesArray }}"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</li>
</ul>
</body>
Live Data Binding
The template examples shown earlier include several examples of data binding that uses the one-way/one-time binding syntax: {{ expression }}. This is illustrated by the following example:
<h3>{{ Name }}</h3>
This type of binding is referred to as one-time binding because the expression is evaluated only once, at the time that the template is rendered. With one-way/one-time binding, if the source data changes after the template has been rendered (in the previous example, if the Name field changes), the rendered value will not be automatically updated.
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:
<input type="text" value="{binding Name}"/>
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.
<h3>{{ binding Name }}</h3>
<input type="text" value="{binding Name}"/>
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:
<input type="text" value="{binding Price, convert=toDollars, convertBack=fromDollars}"/>
A similar syntax can be used to specify a binding mode (one-way or two-way) explicitly:
<input type="text" value="{binding Price, mode=oneWay}"/>
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.
Using the Observer Pattern with JavaScript Objects and Arrays
The observer pattern enables an object to be notified about changes that occur in another object. (The term observer pattern is often misused in JavaScript frameworks to describe event handling based on the addHandler method and similar techniques.) ASP.NET AJAX 4 implements the pattern completely. It adds observer functionality to ordinary JavaScript objects or arrays so that they raise change notifications when they are modified through the Sys.Observer interface. (In the present state of JavaScript, changes that are made directly, without going through the interface, will not raise change notifications.) The observer pattern can be used to establish live bindings between UI elements and objects or arrays, such as those you might get from a JSON Web service.
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">
var imagesArray = [];
Sys.Observer.makeObservable(imageArray);
function onInsert() {
var newImage = { Name: "Name", Description: "Description" };
imagesArray.add(newImage);
}
</script>
<button onclick="onInsert()">Insert</button>
<ul id="imagesList" sys:attach="dataview" class="sys-template"
dataview:data="{{ imagesArray }}"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</li>
</ul>
Posted in: asp.net | Tags: asp.net asp.net 4.0 asp.net ajax ajax instantiation declarative xmlns declarative instantiation javascript live data binding observer patternNew Features in ASP.NET AJAX 4, Part 3
The DataView Control
The DataView control can bind to any JavaScript object or array, or to any ASP.NET AJAX component.
Providing Data to the DataView Control
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:
<ul sys:attach="dataview" class="sys-template"
dataview:data="{{ imagesArray }}"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</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>
<ul id="imagesList" sys:attach="dataview" class="sys-template">
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</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:
<ul sys:attach="dataview" class="sys-template"
dataview:dataprovider="../Services/imagesService.svc"
dataview:fetchOperation="GetImages"
>
<li>
<h3>{{ Name }}</h3>
<div>{{ Description }}</div>
</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.
Additional Features of the DataView Control
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-->
<ul sys:attach="dataview" class=" sys-template"
dataview:dataprovider="../Services/ImageService.svc"
dataview:fetchOperation="GetImages"
dataview:selecteditemclass="myselected"
dataview:sys-key="master"
>
<li sys:command="Select">{{ Name }}</li>
</ul>
<!--Detail View-->
<div class="sys-template"
sys:attach="dataview"
dataview:data="{binding selectedData, source={{master}} }"
>
<div>Name: <input type="text" value="{binding Name}"/></div>
<div>Description: <input type="text" value="{binding Description}"/></div>
</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.
Posted in: asp.net | Tags: asp.net asp.net 4.0 asp.net ajax ajax dataview providing dataASP.NET MVC improvement in Visual studio 2010
ASP.NET MVC was introduced as an add-on framework to ASP.NET 3.5 SP1 in March 2009. Visual Studio 2010 will include a preview of ASP.NET MVC 2. When Visual Studio 2010 ships, it will include the RTM version of ASP.NET MVC 2. The version of ASP.NET MVC 2 that is included in ASP.NET 4 Beta 2 includes new features and capabilities.
Areas Support
Areas let you group controllers and views into sections of a large application in relative isolation from other sections. Each area can be implemented as a separate ASP.NET MVC project that can then be referenced by the main application. This helps manage complexity when you build a large application and makes it easier for multiple teams to work together on a single application.
Data-Annotation Attribute Validation Support
DataAnnotations attributes let you attach validation logic to a model by using metadata attributes. DataAnnotations attributes were introduced in ASP.NET Dynamic Data in ASP.NET 3.5 SP1. These attributes have been integrated into the default model binder and provide a metadata-driven means to validate user input.
Templated Helpers
Templated helpers let you automatically associate edit and display templates with data types. For example, you can use a template helper to specify that a date-picker UI element is automatically rendered for a System.DateTime value. This is similar to field templates in ASP.NET Dynamic Data.
The Html.EditorFor and Html.DisplayFor helper methods have built-in support for rendering standard data types as well as complex objects with multiple properties. They also support basic customization of rendering by letting you apply data-annotation attributes like DisplayName and ScaffoldColumn to the ViewModel object.
Often you want to customize the output from UI helpers even further and have total control over what is generated. The Html.EditorFor and Html.DisplayFor helper methods support this using a templating mechanism that lets you define external templates that can override and control the output rendered. The templates can be rendered on a per-class basis.
From: http://aspnetmvc.info/wp/2009/09/asp-net-mvc-improvement-in-visual-studio-2010/ Posted in: General asp.net | Tags: .net 4.0 mvc visual studio visual studio 2010 asp.net mvc framework data annotation attribute validation support html.editrofor displayname vewmodel