Data binding in the implementation template in ASP.net 2.0

Source: Internet
Author: User
Tags define definition bind commit contains eval insert join
asp.net| Template | data

Templated Data-bound controls provide the fundamental flexibility to display data on the page. You may remember several templated controls (such as the DataList and Repeater controls) in ASP.net v1.x. asp.net 2.0 still supports these controls, but the syntax for binding data in the template has been simplified and improved. This article discusses a variety of ways to bind data in a data-bound control template.

   data-binding expressions

ASP.net 2.0 improves data-binding operations in the template, simplifying the data-binding syntax DataBinder.Eval (Container.DataItem, fieldname) in v1.x to Eval (fieldname). The Eval method, like DataBinder.Eval, can accept an optional format string parameter. The difference between the shortened eval syntax and the DataBinder.Eval is that Eval automatically parses the fields based on the DataItem properties of the nearest container object (such as DataListItem), and DataBinder.Eval needs to use parameters to specify the container. For this reason, eval can only be used in a data-bound control's template, not the page layer. Of course, DataBinder.Eval is still supported on the ASP.net 2.0 page, and you can use it in an environment that does not support simplified Eval syntax.

The following example shows how to use the new simplified eval data binding syntax to bind to the image, label, and Hyperlink controls in the DataList data item template (ItemTemplate).

<asp:datalist id= "DataList1" repeatcolumns= "5" width= "" runat= "datasourceid=" "Server" ObjectDataSource1 ""
<ItemTemplate>
<asp:hyperlink id= "HyperLink1" runat= "server" Navigateurl= ' <%# Eval ("PhotoID", "photoformviewplain.aspx?id={0}")% > ' >
<asp:image id= "Image1" runat= "Server" Imageurl= "<%# Eval (" FileName "," images/thumbs/{0} ")%> '/> </asp:HyperLink>
<asp:label id= "CaptionLabel" runat= "server" text= ' <%# Eval ("Caption")%> '/>
</ItemTemplate>
</asp:DataList> <BR/>
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" Typename= " Datacomponenttableadapters.photostableadapter "selectmethod=" Getphotosforalbum "
Data binding can also be part of the subject definition of a control (theme definition) so that we can change the layout and appearance of the templated control arbitrarily by changing the theme. However, the theme (subject) template can only use eval (or the bind discussed later). Binding to arbitrary user code is prohibited.

   FormView Control

The DataList control iterates through the data items from the data source and outputs ItemTemplate (data item templates) for each data item. This is useful for displaying a list of data items, but typically you want to implement the binding operation of a single data item in a form. To do this, ASP.net 2.0 introduces the FormView control, which can display one data item at a time in any template. The main difference between DetailsView and FormView is that DetailsView has built-in tabular display, and FormView needs to use user-defined display templates. In other respects the FormView and DetailsView object models are very similar. The following example shows a FormView control that is bound to ObjectDataSource. The FormView ItemTemplate property contains image, label, and hyperlink controls for data binding, similar to the previous DataList example.

<asp:formview id= "FormView1" runat= "Server" datasourceid= "ObjectDataSource1"
<ItemTemplate>
<asp:label id= "CaptionLabel" runat= "server" text= ' <%# Eval ("Caption")%> ' font-size= ' 32pt '/><BR/>
<asp:image id= "Image1" runat= "server" Imageurl= ' <%# Eval ("FileName", "images/{0}")%> '/>
<asp:hyperlink id= "HyperLink1" text= "Back to Album" Navigateurl= ' <%# Eval ("albumID", "photosdatalist.aspx?id={0}")%> ' runat= "Server"/>
</ItemTemplate>
</asp:FormView>
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" Typename= " Datacomponenttableadapters.photostableadapter "selectmethod=" Getphoto "
<SelectParameters>
<asp:querystringparameter name= "PhotoID" defaultvalue= "9" querystringfield= "ID"/>
</SelectParameters>
</asp:ObjectDataSource>
FormView is similar to DetailsView and keeps track of the data items that are currently displayed, but when the data source returns to the list, we can also choose to support paging operations for multiple data items. The following example shows a FormView with paging functionality.

<asp:formview id= "FormView1" runat= "Server" datasourceid= "SqlDataSource1"
headertext= "Books for Author" allowpaging= "True" >
<ItemTemplate>
<asp:image id= "Image1" Imageurl= ' <%# Eval ("title_id", "~/images/{0}.gif")%> ' runat= ' server '/>
<asp:label id= "Label1" font-size= "1.2em" font-bold= "true" text= ' <%# Eval ("title")%> ' runat= ' server '/>
<asp:label id= "Label2" text= ' <%# Eval ("price", "{0:c}")%> ' runat= ' server '/>
</ItemTemplate>
</asp:FormView>
<asp:sqldatasource id= "SqlDataSource1" runat= "Server" selectcommand= "select dbo.authors.au_id, dbo.titles.title_id, Dbo.titles.title, Dbo.titles.type, Dbo.titles.price, dbo.titles.notes from dbo.authors INNER JOIN dbo.titleauthor on dbo . authors.au_id = dbo.titleauthor.au_id INNER JOIN dbo.titles on dbo.titleauthor.title_id = dbo.titles.title_id WHERE (dbo . authors.au_id = @au_id) "
connectionstring= "<%$ connectionstrings:pubs%>"
<SelectParameters>
<asp:querystringparameter name= "au_id" defaultvalue= "213-46-8915" querystringfield= "id"/>
</SelectParameters>
</asp:SqlDataSource>

   bidirectional Data Binding

FormView can support automatic Update, insert, and delete operations (similar to DetailsView) through related data source controls. If you want to define an edited or inserted UI, you define a EditItemTemplate or InsertItemTemplate template in addition to defining the data item template (ItemTemplate). In this template, you can bind an input control (such as a text box, check box, or Drop-down list) to a field in a data source. The data bindings in these templates use the bidirectional data binding syntax, which allows FormView to extract values from the template's input controls and pass them to the data source. These data-binding operations replace Eval with the new bind (fieldname) syntax.

Note that data-bound controls that use the BIND syntax must have a good id attribute set.

When the GridView or DetailsView performs an update or insert operation (the columns or fields of these controls will define BoundFields, bound fields), the GridView or DetailsView is responsible for creating the input UI in edit or insert mode, so it can automatically extract these values and pass them to the data source. Because the template contains any user-defined UI controls, bidirectional data-binding syntax is necessary to ensure that templated controls, such as FormView, are aware of the values of those controls that should be extracted from the template when they respond to an update, insert, or delete operation. You can still use the Eval statement for data binding in EditItemTemplate to pass values to the data source. Note that FormView, like DetailsView and GridView, supports the DataKeyNames property, which holds the original values of the primary key dictionaries passed to the update/delete operation, even if the values are not displayed.

FormView supports the DefaultMode property, which specifies the template to be displayed by default, but by default FormView is in read-only mode and the ItemTemplate template is displayed. To convert the UI from read-only mode to edit or insert mode, you can add a button control to the template and set the button's CommandName property to edit or new. In the EditItemTemplate template, you can add buttons and set CommandName to update or Cancel to commit or terminate the update operation. Similarly, you can add a button and set the CommandName to insert or Cancel to commit or terminate the insert operation.

The following example demonstrates the FormView that defines the ItemTemplate and EditItemTemplate templates. The ItemTemplate template contains a control that uses the eval (bidirectional) binding, while the EditItemTemplate template contains a text box control that uses the BIND statement for two-way binding. The primary key field (photoid) is stored in ViewState using the DataKeyNames property. The FormView contains buttons for switching between templates.

<asp:formview id= "FormView1" runat= "Server" datasourceid= "ObjectDataSource1" datakeynames= "PhotoID"
<EditItemTemplate>
<b> Enter a New Caption: </b>
<asp:textbox text= ' <%# Bind ("Caption")%> ' runat= ' Server "id=" Captiontextbox "/> <asp:button" id= "Button1" runat= "server "text=" Update "commandname=" Update "/>
<asp:button id= "Button2" runat= "Server" text= "Cancel" commandname= "Cancel"
</EditItemTemplate>
<ItemTemplate>
<asp:label id= "CaptionLabel" runat= "server" text= ' <%# Eval ("Caption")%> ' font-size= ' 32pt '/><BR/>
<asp:image id= "Image1" runat= "server" Imageurl= ' <%# Eval ("FileName", "images/{0}")%> '/> <BR/>
<asp:button id= "Button3" runat= "Server" text= "Edit Caption ..." Commandname= "Edit"/> <asp:hyperlink id= "HyperLink1" text= "Back to Album" Navigateurl= ' <%# ' Eval ("albumID", " photosdatalist.aspx?id={0} ")%> ' runat= ' server '/>
</ItemTemplate>
</asp:FormView>
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" Typename= " Datacomponenttableadapters.photostableadapter "selectmethod=" Getphoto "updatemethod=" UpdateCaption " oldvaluesparameterformatstring= "Original_{0}" >
<UpdateParameters>
<asp:parameter name= "Caption"/>
<asp:parameter name= "Original_photoid"/>
</UpdateParameters>
<SelectParameters>
<asp:querystringparameter name= "PhotoID" defaultvalue= "9" querystringfield= "ID"/>
</SelectParameters>
</asp:ObjectDataSource>
The GridView and DetailsView also support templated UIs, which are implemented by adding TemplateField to the Columns or Fields collection. TemplateField supports the use of ItemTemplate, EditItemTemplate, and InsertItemTemplate (DetailsView only) to specify the UI for fields in different display modes of the control. Like the FormView example above, bidirectional data binding in EditItemTemplate or InsertItemTemplate also allows the GridView or DetailsView to extract values from the controls of these templates. The most common use of TemplateField is to add validator controls to EditItemTemplate to publicly authenticate the GridView or DetailsView operations. The following example illustrates this technique.


......
<asp:gridview id= "GridView1" runat= "Server" datasourceid= "ObjectDataSource1" autogeneratecolumns= "False" Allowpaging= "true" allowsorting= "true" datakeynames= "albumID"
<Columns>
<asp:commandfield showeditbutton= "True"/>
<asp:boundfield readonly= "True" headertext= "albumID" datafield= "albumID" sortexpression= "albumID"/>
<asp:templatefield headertext= "Albumname" sortexpression= "Albumname" itemstyle-wrap= "false"
<ItemTemplate>
<asp:label id= "Label1" runat= "server" text= ' <%# Eval ("Albumname")%> ' > </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:textbox id= "TextBox1" runat= "server" text= ' <%# ' Bind ("Albumname")%> ' > </asp:TextBox>
<asp:requiredfieldvalidator controltovalidate= "TextBox1" errormessage= "Albumname cannot be empty" id= " RequiredFieldValidator1 "display=" Dynamic "runat=" Server ">* </asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
......
</asp:GridView> <BR/>
<asp:validationsummary id= "ValidationSummary1" runat= "Server"/>
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" convertnulltodbnull= "true"
Typename= "Datacomponenttableadapters.albumstableadapter" selectmethod= "Getalbumsbyowner" UpdateMethod= "Update" oldvaluesparameterformatstring= "Original_{0}" >
......
</asp:ObjectDataSource>
Another use of TemplateField is to customize controls that give the GridView or DetailsView column/field input values. For example, you can place a DropDownList in the EditItemTemplate of TemplateField, allowing the user to select from a list of predefined values. The following example illustrates this technique. Note that the Drop-down list in the example is bound to its own data source control to get the list values dynamically.

<asp:templatefield headertext= "owner" sortexpression= "owner"
<ItemTemplate>
<asp:label id= "Label2" runat= "server" text= ' <%# Eval ("Owner")%> ' > </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:dropdownlist datasourceid= "ObjectDataSource2" datatextfield= "owner" datavaluefield= "owner" id= "DropDownList2" runat= "Server" Selectedvalue= ' <%# Bind ("Owner")%> ' >
</asp:DropDownList>
</EditItemTemplate>
<itemstyle wrap= "False"/>
</asp:TemplateField>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.